2015-12-13 55 views
1

我得到以下错误'TypeError:类型'NoneType'的对象对于下面的程序没有len()'。为什么我不能遍历列表并将其与另一个列表进行比较?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 
+0

简要说明:'append()'将对象改变位置并返回'None'。不要将'append()'操作的结果保存回同一个引用。只需要执行'word_list.append(word)'操作。 – TigerhawkT3

回答

1

list.append返回None

以下行:

word_list = word_list.append(word) 

应改为:

word_list.append(word) 

否则,word_list成为None导致TypeError以后。

相关问题