在Python Shell中,我输入:

aList = ['a', 'b', 'c', 'd']  
for i in aList:  
    print(i)

得到了

a  
b  
c  
d  

但是当我尝试时:

aList = ['a', 'b', 'c', 'd']  
aList = aList.append('e')  
for i in aList:  
    print(i) 

得到了

Traceback (most recent call last):  
  File "<pyshell#22>", line 1, in <module>  
    for i in aList:  
TypeError: 'NoneType' object is not iterable  

有人知道发生了什么吗?我该如何解决/解决?

有帮助吗?

解决方案

list.append 是修改现有列表的方法。它不会返回新列表 - 它返回 None, ,就像大多数修改列表的方法一样。简单地做 aList.append('e') 您的列表将获得附加元素。

其他提示

通常,您想要的是公认的答案。但是,如果您希望覆盖值并创建新列表的行为(在某些情况下是合理的),那么您可以做的是使用“ Splat Operator”,也称为“列表”拆开:

aList = [*aList, 'e']
#: ['a', 'b', 'c', 'd', 'e']

或者,如果您需要支持Python 2,请使用 + 操作员:

aList = aList + ['e']
#: ['a', 'b', 'c', 'd', 'e']

^在许多情况下,您想避免突变的副作用 .append(). 。一个人,想象一下,您想将某些内容附加到您作为函数参数的列表中。使用该函数的人可能不会期望他们提供的列表将被更改。使用这样的东西可以保持您的功能 “纯的” 没有 “副作用”.

删除第二行 aList = aList.append('e') 并仅使用 aList.append("e"), ,这应该摆脱这个问题。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top