python - 在什么情况下列表会变成 python 中的字符串?

标签 python

大家好,我这里有一小段代码让我很头疼。在这个函数中,我定义了一个名为 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/

相关文章:

python - 我的 Pyramid 不喜欢 Pandas

具有一些功能的 Python 键盘记录器

python - 检查变量的多个值

python - 如何替换尺寸不均匀的文件中的某些列

python - 搜索字符串并获取行和列值

Python Selenium 绕过检测?

Python/Numpy 快速选择列表中第 n 个 block 的方法

python - 如何重构此代码片段以使其更高效?

python - OpenCV:为 OCR 隔离车牌字符

python::遍历嵌套的 JSON 结果