追加将我的列表变为 NoneType
在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
有人知道发生了什么事吗?我该如何解决/解决它?
In Python Shell, I entered:
aList = ['a', 'b', 'c', 'd']
for i in aList:
print(i)
and got
a
b
c
d
but when I tried:
aList = ['a', 'b', 'c', 'd']
aList = aList.append('e')
for i in aList:
print(i)
and got
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
for i in aList:
TypeError: 'NoneType' object is not iterable
Does anyone know what's going on? How can I fix/get around it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
list.append
是修改现有列表的方法。它不会返回新列表 - 它返回None
,就像大多数修改列表的方法一样。只需执行aList.append('e')
,您的列表就会附加该元素。list.append
is a method that modifies the existing list. It doesn't return a new list -- it returnsNone
, like most methods that modify the list. Simply doaList.append('e')
and your list will get the element appended.删除第二行
aList = aList.append('e')
并仅使用aList.append("e")
,这应该可以解决该问题。Delete your second line
aList = aList.append('e')
and use onlyaList.append("e")
, this should get rid of that problem.一般来说,您想要的是公认的答案。但是,如果您想要覆盖值并创建新列表的行为(在某些情况下这是合理的^),您可以使用“splat 运算符”,也称为列表解包:
或者,如果您需要支持 python 2,使用
+
运算符:^ 在很多情况下,您希望避免使用
.append()
进行变异的副作用。首先,假设您想要将某些内容附加到作为函数参数的列表中。无论谁使用该函数,都可能不希望他们提供的列表会发生更改。使用这样的东西可以让你的函数“纯粹”而无需“副作用”。Generally, what you want is the accepted answer. But if you want the behavior of overriding the value and creating a new list (which is reasonable in some cases^), what you could do instead is use the "splat operator", also known as list unpacking:
Or, if you need to support python 2, use the
+
operator:^ There are many cases where you want to avoid the side effects of mutating with
.append()
. For one, imagine you want to append something to a list you've taken as a function argument. Whoever is using the function probably doesn't expect that the list they provided is going to be changed. Using something like this keeps your function "pure" without "side effects".有时,当您忘记在另一个函数末尾返回一个函数并传递一个空列表(解释为 NoneType)时,就会出现此错误。
从这个:
到这个:
Sometimes this error appears when you forgot to return a function at the end of another function and passed an empty list, interpreted as NoneType.
from this:
to this: