【问题标题】:"TypeError: object of type 'NoneType' has no len()" after using remove() on a list [duplicate]“TypeError:'NoneType'类型的对象没有len()”在列表上使用remove()后[重复]
【发布时间】:2018-05-31 00:46:25
【问题描述】:

我有这个代码:

list_of_directions = ['right', 'left', 'up', 'down']
new_list = list_of_directions.remove('right')

print(len(new_list))

但我收到错误消息

TypeError: 'NoneType' 类型的对象没有 len()

我以为我了解.remove() 的工作原理,但也许我不了解?

为什么会出现这个错误?

【问题讨论】:

    标签: python python-3.x list


    【解决方案1】:

    list.remove 是一个就地操作。它返回None

    您需要在new_list 的单独行中执行此操作。换句话说,而不是new_list = list_of_directions.remove('right')

    new_list = list_of_directions[:]
    
    new_list.remove('right')    
    

    在上述逻辑中,我们在删除特定元素之前将new_list 分配给list_of_directions 的副本。

    注意分配给list_of_directions副本 的重要性。这是为了避免new_list 以不希望的方式更改为list_of_directions 的可能性很大。

    docs 中明确指出了您所看到的行为:

    您可能已经注意到 insertremovesort 等方法 只修改列表没有打印返回值——它们返回 默认None。这是所有可变数据的设计原则 Python 中的结构。

    【讨论】:

    • 注意:如果目标是保留原始的list_of_directions,您需要反转操作;使new_list = list_of_directions[:]然后调用new_list.remove('right')。否则,这两个列表最终会得到相同的内容,这是毫无意义的。或者,将这两个操作组合成一个列表理解:new_list = [d for d in list_of_directions if d != 'right'](在行为上有所不同,因为如果存在多个'right' 实例,它将删除它们,但在这种情况下可能需要这样做)。
    猜你喜欢
    • 2016-03-18
    • 2021-03-03
    • 2015-07-30
    • 1970-01-01
    • 2021-10-21
    • 2018-08-14
    • 2016-06-06
    • 1970-01-01
    • 2022-11-17
    相关资源
    最近更新 更多