【发布时间】:2016-03-18 20:30:23
【问题描述】:
对于下面的程序,我收到以下错误“TypeError:'NoneType' 类型的对象没有 len()”。为什么我不能遍历一个列表并将其与另一个列表进行比较?
word_list = list()
while True:
file_name = raw_input('Enter file name: ')
if len(file_name) < 1: exit()
try:
file = open(file_name)
break
except:
print 'Please enter a valid file name.'
continue
for line in file:
line = line.rstrip()
words = line.split()
for word in words:
if len(word_list) <1:
word_list = word_list.append(word)
else:
if not word in word_list:
word_list = word_list.append(word)
word_list = word_list.sort()
print word_list
【问题讨论】:
-
简单地说:
append()对对象进行原地变异并返回None。不要将append()操作的结果保存回相同的引用。只需执行操作,word_list.append(word)。
标签: python list loops for-loop iteration