Python 追加将我的列表变为 NoneType

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3840784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:57:32  来源:igfitidea点击:

Appending turns my list to NoneType

pythonmutators

提问by user460847

In Python Shell, I entered:

在 Python Shell 中,我输入:

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?

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

采纳答案by Thomas Wouters

list.appendis a method that modifies the existing list. It doesn't return a new list -- it returns None, like most methods that modify the list. Simply do aList.append('e')and your list will get the element appended.

list.append是一种修改现有列表的方法。它不返回新列表——它返回None,就像大多数修改列表的方法一样。只需这样做aList.append('e'),您的列表就会附加元素。

回答by aletelecomm

Delete your second line aList = aList.append('e')and use only aList.append("e"), this should get rid of that problem.

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

回答by SCB

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:

通常,您想要的是公认的答案。但是,如果您想要覆盖值并创建新列表的行为(在某些情况下这是合理的^),您可以做的是使用“splat 运算符”,也称为列表解包:

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

Or, if you need to support python 2, use the +operator:

或者,如果您需要支持 python 2,请使用+运算符:

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


^ 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".

^ 在很多情况下,您希望避免使用.append(). 一方面,假设您想将某些内容附加到您作为函数参数的列表中。使用该功能的人可能不希望他们提供的列表会发生变化。使用这样的东西可以让你的功能“纯粹”而没有“副作用”