非类型的对象没有长度错误

2024-10-04 11:32:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了以下函数来将列表的元素添加到字符串中


import random 
import string 

def printmatches (word,x):
    y = len(word)
    z = [" "] *y 
    i = 0 
    while i<y:
        if word[i] == x: 
            z[i] = x 
        else:
            z[i] = " "  
        i+=1

    return (z)

def append(string,chars): ##append list to a string
    q = 0
    while q < len(string): 
        if string[q] == " " and chars[q] != " ":
            string[q] = chars[q]
        q+=1  

x = random.randint(0,55899)

def convertlist(x):
    q = " "
    a = 0
    while (a < len(x)):
        q+=x[a]
        a+=1
    return (q) 

try:
    f = open('words.txt', 'r')
    s = " "
    s = f.readline()

    L = s.split()

    word = L[x]

    f.close()

except IOError:
    print('file not found')

q=0

print word

print (printmatches('ereesvox','o') == [" "] * 8)  
current = [" "] * len(word)  
c = 0
char = " " 
while char != word and q < 3 and c <35: 
    char = raw_input (" ") 
    c+=1
    ##current.append(printmatches(word,char)) 
    append(current, printmatches(word,char)) 
    str = (append(current, printmatches(word,char)))
    if (convertlist(str) == word): 
        print 'Congratulations, you have won'
    if printmatches(word,char) == [" "]*len(word):    
        print "You have ", (2-q), " guesses left"   
        q+=1 
    if (q == 3):
        print "Game over"
    print ' '.join(current)     



x是一个列表,但当我执行代码时,它的类型被解释为非类型,我得到错误消息,因为我试图访问x中的元素并比较其长度。我如何解决这个问题


Tags: and元素列表stringlenifdefcurrent
2条回答

在使用x执行任何操作之前,请进行检查,以查看x不是None或list以外的任何其他类型。 像下面这样

def convertlist(x):
    q = " "
    a = 0
    if isinstance(x, list):
        while (a < len(x)):
            q+=x[a]
            a+=1
    return (q)
def append(string,chars): ##append list to a string
    q = 0
    while q < len(string): 
        if string[q] == " " and chars[q] != " ":
            string[q] = chars[q]
        q+=1  

这不会显式返回值,因此隐式返回None

(名称string在这里也是一个非常糟糕的选择:首先,您希望传递的是一个列表而不是一个字符串(因为正如您之前所了解的,您无法修改这样的字符串),其次它隐藏了导入的string模块。但是,您的代码没有使用string模块,因此您不应该import(首先,这是一个问题。)

str = (append(current, printmatches(word,char)))

现在strNone,因为它是append调用的结果

if (convertlist(str) == word): 

现在,我们尝试使用Noneconvertlist,这当然不起作用,因为我们希望传入一个列表

def convertlist(x):
    q = " "
    a = 0
    while (a < len(x)):
        q+=x[a]
        a+=1
    return (q) 

。。。因此这里lenNone无效


从函数中获取信息的自然方式是return该信息。在append中创建一个新字符串,并return它;然后你就可以用你想用的方法来使用结果了。另外,由于您正在创建一个新对象,因此实际上可以再次传入字符串

除了,我不知道为什么这个函数被称为append,因为尽管有注释,它似乎并不打算做任何这样的事情

相关问题 更多 >