gpt4 book ai didi

python - 在列表上使用remove()后"TypeError: object of type ' NoneType ' has no len()"

转载 作者:行者123 更新时间:2023-11-30 22:14:04 24 4
gpt4 key购买 nike

我有这个代码:

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

print(len(new_list))

但我收到错误消息

TypeError: object of type 'NoneType' has no len()

我以为我明白了 .remove()有效,但也许我没有?

为什么我会收到此错误?

最佳答案

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 中明确注明。 :

You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None. This is a design principle for all mutable data structures in Python.

关于python - 在列表上使用remove()后"TypeError: object of type ' NoneType ' has no len()",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50615169/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com