我正在玩海象运算符(与 this question 有关):=
,它将在 python 3.8 中可用。
与
def f(x):
return x**3
old_list = = list(range(9))
这按预期工作(不要介意这个例子毫无意义......):
new_list = [fx for x in old_list if (fx := f(x)) in {1, 8, 343}]
# [1, 8, 343]
这是有效的并且可以运行,但是会返回一些意外的东西:
new_list = [fx := f(x) for x in old_list if fx in {1, 8, 343}]
# []
这里发生了什么?
TL;DR 你的第二个不是“那个”有效的:
>>> old_list = list(range(9))
>>> f = lambda x: x ** 3
>>> [fx := f(x) for x in old_list if fx in {1, 8, 343}]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
NameError: name 'fx' is not defined
>>>
说明
在您的第一个列表理解中,[fx for x in old_list if (fx := f(x)) in {1, 8, 343}]
,fx :=
在其外部创建一个变量:
>>> old_list = list(range(9))
>>> f = lambda x: x ** 3
>>> [fx for x in old_list if (fx := f(x)) in {1, 8, 343}]
[1, 8, 343]
>>> fx
512
如果你之后运行 [fx := f(x) for x in old_list if fx in {1, 8, 343}]
,它会像这样:
for x in old_list
将 x 绑定(bind)到 0
如果 fx 在 {1, 8, 343}
中,fx 是旧的 512
,这是错误的
- 因为 if 为假,“select”(左边)部分没有执行,没有调用 f,没有重新绑定(bind) fx,fx 仍然是 512。
- 将 x 指定为 old_list 的第 2 个元素,即 1
- ...
我们可以像这样仔细检查这个解释:
>>> [print("no no no") for x in old_list if fx in {1, 8, 343}]
[]
no no no
永远不会打印,所以这一边永远不会执行(因为 fx
是 512,不在 set
中)。
我是一名优秀的程序员,十分优秀!