我正在尝试将 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/