Add*_*son 2 python list python-3.x
我有这个代码:
list_of_directions = ['right', 'left', 'up', 'down']
new_list = list_of_directions.remove('right')
print(len(new_list))
Run Code Online (Sandbox Code Playgroud)
但我收到错误消息
类型错误:“NoneType”类型的对象没有 len()
我以为我了解.remove()工作原理,但也许我不明白?
为什么我会收到这个错误?
list.remove是就地操作。它返回None。
您需要在单独的行中执行此操作到new_list。换句话说,而不是new_list = list_of_directions.remove('right'):
new_list = list_of_directions[:]
new_list.remove('right')
Run Code Online (Sandbox Code Playgroud)
在上面的逻辑中,我们在删除特定元素之前分配new_list给的副本list_of_directions。
注意分配到的重要性复制的list_of_directions。这是为了避免极有可能以不希望的方式new_list改变的情况list_of_directions。
您所看到的行为在文档中明确指出:
您可能已经注意到,像
insert,remove或者sort只修改列表的方法没有打印返回值——它们返回默认值None。这是 Python 中所有可变数据结构的设计原则。
| 归档时间: |
|
| 查看次数: |
386 次 |
| 最近记录: |