【问题标题】:TypeError: object of type 'NoneType' has no len() while iterating through a list [duplicate]TypeError:“NoneType”类型的对象在遍历列表时没有 len() [重复]
【发布时间】: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


【解决方案1】:

list.append 返回None

下面一行:

word_list = word_list.append(word)

应替换为:

word_list.append(word)

否则,word_list 将变为 None,从而导致稍后出现 TypeError

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    • 2015-07-30
    • 1970-01-01
    • 2018-08-14
    • 2016-06-06
    • 1970-01-01
    • 2020-05-26
    相关资源
    最近更新 更多