大家好,我这里有一小段代码让我很头疼。在这个函数中,我定义了一个名为 word
的列表,突然间列表变成了一个字符串。我不知道这怎么可能:
def find_best_shift(wordlist, text):
words = []
word = []
for x in range(0, 27):
apply_shift(text, x)
for character in text:
print (type(word))
if (character in ALPHABET) or (character in alphabet):
word.append(character)
else:
wor = ''.join(word)
words.append(wor)
word = []
for word in words:
y = is_word(wordlist, word)
if y == True:
return x
你们注意到打印语句 print(type(word))
。使用此语句,我得到以下输出:
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'str'>
然后它给了我以下错误:
File "C:\Users\usuario\Documents\Python Projects\ps4\ps4.py", line 264, in find_best_shift
word.append(character)
AttributeError: 'str' object has no attribute 'append'
如有任何帮助,我将不胜感激!
最佳答案
for word in words:
在移动到 x
的下一个值之前,将相同的名称 (word
) 重新指定为 words
列表的一个元素。将其更改为其他内容。
for item in words:
重用名称会引起一些有趣的麻烦:(
别忘了更新
y = is_word(wordlist, word)
到
y = is_word(wordlist, item)
我会简化
if y == True:
为了简单
if y:
如果您开始将条件链接在一起,则与 bool 文字的显式比较会产生一些有趣的结果。
关于python - 在什么情况下列表会变成 python 中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18626926/