Python 在 for 循环中列出 append()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41452819/
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
List append() in for loop
提问by jim basquiat
In Python, trying to do the most basic append function to a list with a loop: Not sure what i am missing here:
在 Python 中,尝试使用循环对列表执行最基本的 append 函数:不确定我在这里缺少什么:
a=[]
for i in range(5):
a=a.append(i)
a
returns:
'NoneType' object has no attribute 'append'
返回:
'NoneType' object has no attribute 'append'
回答by Rafael Aguilar
The list.append
function does not return any value(but None
), it just add the value to the list you are using to call that method.
该list.append
函数不返回任何值(但是None
),它只是将值添加到您用来调用该方法的列表中。
In the first loop round you will assign None
(because the no-return of append
) to a
, then in the second round it will try to call a.append
, as a is None
it will raise the Exception you are seeing
在第一轮循环中,您将分配None
(因为没有返回append
)到a
,然后在第二轮中它将尝试调用a.append
,因为a is None
它会引发您看到的异常
You just need to change it to:
您只需要将其更改为:
a=[]
for i in range(5):
a.append(i)
a # the list with the new items.
Edit: As Juan said in comments it does return something, None
编辑:正如胡安在评论中所说,它确实返回了一些东西, None
回答by linusg
You don't need the assignment, list.append(x)
will always append x
to a
and therefore there's no need te redefine a
.
您不需要分配,list.append(x)
将始终附加x
到a
,因此不需要重新定义a
。
a = []
for i in range(5):
a.append(i)
print(a)
is all you need. This works because list
s are mutable.
是你所需要的全部。这是有效的,因为list
s 是可变的。
Also see the docs on data structures.
回答by Muntaser Ahmed
No need to re-assign.
无需重新分配。
a=[]
for i in range(5):
a.append(i)
a