如何附加到空列表的末尾? [英] How to append to the end of an empty list?
问题描述
我有一个清单:
list1=[]
列表的长度未确定,所以我试图将对象附加到 list1 的末尾,如下所示:
the length of the list is undetermined so I am trying to append objects to the end of list1 like such:
for i in range(0, n):
list1=list1.append([i])
但我的输出不断出现此错误:AttributeError: 'NoneType' object has no attribute 'append'
But my output keeps giving this error: AttributeError: 'NoneType' object has no attribute 'append'
这是因为 list1 从空列表开始吗?如何修复此错误?
Is this because list1 starts off as an empty list? How do I fix this error?
推荐答案
append
实际上改变列表.此外,它需要一个项目,而不是一个列表.因此,您只需要
append
actually changes the list. Also, it takes an item, not a list. Hence, all you need is
for i in range(n):
list1.append(i)
(顺便说一下,在这种情况下,您可以使用 range(n)
.)
(By the way, note that you can use range(n)
, in this case.)
我假设您的实际使用更复杂,但您可能可以使用列表推导式,这对于此而言更加 Pythonic:
I assume your actual use is more complicated, but you may be able to use a list comprehension, which is more pythonic for this:
list1 = [i for i in range(n)]
或者,在这种情况下,在 Python 2.x range(n)
实际上已经创建了您想要的列表,尽管在 Python 3.x 中,您需要 list(range(n))
.
Or, in this case, in Python 2.x range(n)
in fact creates the list that you want already, although in Python 3.x, you need list(range(n))
.
这篇关于如何附加到空列表的末尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!