Python 将值附加到空列表的最佳实践

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30680808/
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-19 08:48:51  来源:igfitidea点击:

Best practice to append value to an empty list

pythonlistinitialization

提问by ferdy

I'm just curious about the following code fragment not working, which should initialize an empty list and on-the-fly append an initial value. The second fragment is working. What's wrong with it? Is there a best practice for such initializing?

我只是对以下代码片段不工作感到好奇,它应该初始化一个空列表并即时附加一个初始值。第二个片段正在工作。它出什么问题了?这种初始化有最佳实践吗?

>>> foo = [].append(2)
>>> print foo
None
>>> foo = []
>>> foo.append(2)
>>> print foo
[2]

EDIT: Seems I had a misunderstanding in the syntax. As already pointed out below, append always returns None as a result value. What I first thought was that [] would return an empty list object where the append should put a first element in it and in turn assigns the list to foo. That was wrong.

编辑:似乎我对语法有误解。正如下面已经指出的, append 总是返回 None 作为结果值。我首先想到的是 [] 将返回一个空列表对象,其中 append 应该在其中放置第一个元素,然后将列表分配给 foo。那是错误的。

采纳答案by Alexander McFarlane

The actual reason why you can't do either of the following,

您不能执行以下任一操作的实际原因,

l = [].append(2)
l = [2,3,4].append(1)

is because .append()always returns Noneas a function return value. .append()is meant to be done in place.

是因为.append()总是None作为函数返回值返回。.append()旨在就地完成。

See herefor docs on data structures. As a summary, if you want to initialise a value in a list do:

有关数据结构的文档,请参见此处。总而言之,如果要初始化列表中的值,请执行以下操作:

l = [2]

If you want to initialise an empty list to use within a function / operation do something like below:

如果要初始化一个空列表以在函数/操作中使用,请执行以下操作:

l = []
for x in range(10):
    value = a_function_or_operation()
    l.append(value)

Finally, if you really want to do an evaluation like l = [2,3,4].append(), use the +operator like:

最后,如果你真的想做一个像 那样的评估l = [2,3,4].append(),使用+像这样的运算符:

l1 = []+[2]
l2 = [2,3,4] + [2]
print l1, l2
>>> [2] [2, 3, 4, 2]   

This is generally how you initialise lists.

这通常是您初始化列表的方式。