在Python中附加到列表理解将返回None [英] Appending to a list comprehension in Python returns None
问题描述
这是出于好奇而不是试图将其用于实际目的的问题.
This is a question out of curiosity rather than trying to use it for a practical purpose.
考虑一下,我有一个简单的示例,其中我通过列表理解生成了一个列表:
Consider I have the following simple example where I generate a list through list comprehension:
>>> a = [1, 2, 3]
>>> b = [2 * i for i in a]
>>> b
[2, 4, 6]
>>> b.append(a)
>>> b
[2, 4, 6, [1, 2, 3]]
但是,如果我尝试一次完成所有操作
However if I try and do this all in one action
>>> a = [1, 2, 3]
>>> b = [2 * i for i in a].append(a)
>>> b == None
True
结果返回 None
.有什么理由吗?
The result returns None
. Is there any reason why this is the case?
我本以为这样的动作会返回第一个示例中的答案,或者抛出错误.
I would have thought that an action like this would either return an answer like in the first example or throw an error.
作为参考,我使用的是Python 3.6.5
For reference I'm using Python 3.6.5
推荐答案
append
仅适用于变量,而不适用于列表文字,因为它会更新列表对象本身,并且不会返回结果列表.
append
only works on variables, not list literals, since it updates the list object itself and does not return the resulting list.
如@Tomalak所述,在简单列表上运行类似的操作也会返回 None
As @Tomalak mentioned noted, running a similar operation on a simple list also returns None
>>> [1, 2, 3].append(4) == None
True
这篇关于在Python中附加到列表理解将返回None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!