在Python Shell中,我输入了:
aList = ['a', 'b', 'c', 'd']
for i in aList:
print(i)
Run Code Online (Sandbox Code Playgroud)
得到了
a
b
c
d
Run Code Online (Sandbox Code Playgroud)
但是当我尝试:
aList = ['a', 'b', 'c', 'd']
aList = aList.append('e')
for i in aList:
print(i)
Run Code Online (Sandbox Code Playgroud)
得到了
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
for i in aList:
TypeError: 'NoneType' object is not iterable
Run Code Online (Sandbox Code Playgroud)
有谁知道发生了什么?我该如何解决/解决它?
Tho*_*ers 42
list.append是一种修改现有列表的方法.它不返回新列表 - 它返回None,就像大多数修改列表的方法一样.只需这样做aList.append('e'),您的列表将附加元素.
通常,您想要的是公认的答案。但是,如果您想要覆盖值并创建新列表的行为(在某些情况下这是合理的^),您可以做的是使用“splat 运算符”,也称为列表解包:
aList = [*aList, 'e']
#: ['a', 'b', 'c', 'd', 'e']
Run Code Online (Sandbox Code Playgroud)
或者,如果您需要支持 python 2,请使用+运算符:
aList = aList + ['e']
#: ['a', 'b', 'c', 'd', 'e']
Run Code Online (Sandbox Code Playgroud)
^ 在很多情况下,您希望避免使用.append(). 一方面,假设您想将某些内容附加到您作为函数参数的列表中。使用该功能的人可能不希望他们提供的列表会发生变化。使用这样的东西可以让你的函数保持“纯净”而没有“副作用”。
| 归档时间: |
|
| 查看次数: |
34897 次 |
| 最近记录: |