python - list.append 在 python 3 : nonetype is not iterable?

标签 python

我正在尝试将 romeo.txt 中的每个单词添加到一个空列表中。
我认为这段代码没问题,但 python3 返回一个回溯说

File "test.py", line 13, in <module> if i in lst: TypeError: argument of type 'NoneType' is not iterable

这是我的代码:

fh = open("romeo.txt")
lst = list()
words = fh.read()
list1 = words.split()
for i in list1:
    if i in lst:
        continue
    else:
        lst = lst.append(i)
lst = lst.sort()
print(lst)

最佳答案

说明

你犯了同样的错误两次。您首先犯此错误的地方以及您收到当前错误的原因是因为:

lst = lst.append(i)

append 方法实际上执行了适当的append。该调用的实际 返回值将是None,因为它不返回任何内容。它不需要,因为它完成了列表中的工作。

所以,要缩小到底发生了什么。当你执行 lst = lst.append(i) 时。 lst 现在将保留 None。因此,下次它执行循环时,您会到达这里:

if i in lst:

您正在检查 i 是否在 None 中。因为现在 lst 将保持 None,所以正是在这里引发了错误消息,并且您看到了 Traceback

复制:

   >>> 'a' in None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument of type 'NoneType' is not iterable

解决方案

要解决这个问题,您只需要像这样执行追加:

lst.append(i)

第二个错误

你在这里调用 sort 时也犯了同样的错误:

lst = lst.sort()

它又是一种就地执行其工作的方法,因此您只需要:

lst.sort()

额外说明

不要忘记在代码结束时关闭文件(或者当您使用完文件时:

fh.close()

理想情况下,最好始终使用上下文管理器,如另一个答案 here 中所述。 .由于上下文管理器为您完成了所有“清理”工作。

关于python - list.append 在 python 3 : nonetype is not iterable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44916934/

相关文章:

python - 警告 : `pyenv init -` no longer sets PATH when starting the terminal window

使用通用函数的 Python numpy 网格转换

python - pygame的声音格式差异

python - 将分隔符分隔的字符串转换为 numpy 数组的有效方法

python - Flask View 中装饰器的顺序是否重要?

python - 我如何发送带有 python 和动态值的发布请求?

python - 有没有办法使用 Pycuda 检索特定值的索引?

python - 如何在 output.csv 文件中包含 "for"循环变量

python - 用于分组的窗口函数

python - 如何跟踪多处理和 pool.map 的状态?