我编写了以下函数来将列表的元素添加到字符串中
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中的元素并比较其长度。我如何解决这个问题
在使用x执行任何操作之前,请进行检查,以查看x不是None或list以外的任何其他类型。 像下面这样
这不会显式返回值,因此隐式返回
None
(名称
string
在这里也是一个非常糟糕的选择:首先,您希望传递的是一个列表而不是一个字符串(因为正如您之前所了解的,您无法修改这样的字符串),其次它隐藏了导入的string
模块。但是,您的代码没有使用string
模块,因此您不应该import
(首先,这是一个问题。)现在
str
是None
,因为它是append
调用的结果现在,我们尝试使用
None
来convertlist
,这当然不起作用,因为我们希望传入一个列表。。。因此这里
len
对None
无效从函数中获取信息的自然方式是
return
该信息。在append
中创建一个新字符串,并return
它;然后你就可以用你想用的方法来使用结果了。另外,由于您正在创建一个新对象,因此实际上可以再次传入字符串除了,我不知道为什么这个函数被称为
append
,因为尽管有注释,它似乎并不打算做任何这样的事情相关问题 更多 >
编程相关推荐