为什么我的 Python Interactive shell 中的列表理解附加了一个无列表?

Why does list comprehension in my Python Interactive shell append a list of Nones?

我正在我的交互式 shell

中测试一些 Django 功能

这是我尝试探测这些对象的尝试,请注意末尾的 Nones 列表

>>> [print(foo) for foo in CharacterSkillLink.objects.all() if foo.speciality]
Streetwise (Street Countdown) Roran
[None]

以及更正统的列表理解:

>>> [print(foo) for foo in range(1,10)]
1
2
3
4
5
6
7
8
9
[None, None, None, None, None, None, None, None, None]

连续九个无。

为什么我会得到那个?

因为printreturns一个值,即None。它打印的内容和它 returns 是两个不同的东西。

这是因为,你使用Python3.x,其中printfunctionreturnsNone后打印到控制台,因此您将获得此输出。然而,如果您使用了 Python 2.x,您将正确地得到打印函数的 SyntaxError。

一个更好的例子是这个(在 python 2.x 中,因为你的例子在 python 2.x 中不起作用)

>>> b = []
>>> [b.append(i) for i in range(10)]
...[None, None, None, None, None, None, None, None, None, None]
>>> print b
...[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

如果你想打印东西并将其添加到列表中,应该是这样的:

[(print(foo) or foo) for foo in CharacterSkillLink.objects.all() if foo.speciality]

但是,在我看来,不要使用这样的东西,因为一段时间后可能会变丑。