追加将我的列表转换为NoneType

use*_*847 29 python mutators

在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'),您的列表将附加元素.

  • @kindall:"不返回任何东西"应该是"实际上,如果方法没有`return`语句并且隐式返回`None`"也是一样的.和."变异对象的方法几乎从不返回值,pop是值得注意的例外." (2认同)
  • 您在技术上是正确的...最好的正确方法! (2认同)

ale*_*omm 5

删除第二行aList = aList.append('e')并仅使用aList.append("e"),这应该可以解决该问题。


SCB*_*SCB 5

通常,您想要的是公认的答案。但是,如果您想要覆盖值并创建新列表的行为(在某些情况下这是合理的^),您可以做的是使用“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(). 一方面,假设您想将某些内容附加到您作为函数参数的列表中。使用该功能的人可能不希望他们提供的列表会发生变化。使用这样的东西可以让你的函数保持“纯净”而没有“副作用”