如何在python中以什么顺序评估列表推导 [英] How list comprehensions are evaluated in python and in what order
问题描述
我有两个列表推导,其中在不同位置定义了条件.
I have two list comprehensions where conditions are defined in different places.
>>> [ x**2 if x%2==0 else x**3 if x%3==0 else 0 for x in range(10)]
[0, 0, 4, 27, 16, 0, 36, 0, 64, 729]
>>> [ x**2 if x%2==0 for x in range(10) ]
File "<stdin>", line 1
[ x**2 if x%2==0 for x in range(10) ]
^
SyntaxError: invalid syntax
但是,如果我这样做:
>>> [ x**2 for x in range(10) if x%2==0 ]
[0, 4, 16, 36, 64]
>>>
有效.
现在,令人困惑的部分是如何评估订单.有什么区别?
Now the confusing part is how the order is evaluated. What is the difference?
推荐答案
您在这里有两个不同的概念.
You have two different concepts confused here.
x**2 if x%2==0 else x**3
之类的表达式是条件表达式.它们可以被链接,但是else
是非可选的-因为这是一个自包含表达式,计算得出的是单个特定值. else x**3
是必需的,因为无论何时x % 2 == 0
都不是Python,Python都必须知道表达式的计算结果.
An expression like x**2 if x%2==0 else x**3
is a conditional expression. They can be chained, but the else
is not optional - because this is a self-contained expression that evaluates to a single, specific value. The else x**3
is required because Python has to know what the expression evaluates to whenever it is not the case that x % 2 == 0
.
在列表理解中,当您编写[x**2 for x in range(10) if x%2==0]
之类的内容时,if
子句用于过滤 in range(10)
中找到的x
值, for
计算结果列表中的哪些元素.此处不允许else
,因为目的是完全不同的.
In a list comprehension, when you write things like [x**2 for x in range(10) if x%2==0]
, the if
clause is used to filter the x
values found in range(10)
, for
which elements of the resulting list are computed. There is no else
permitted here because the purpose is entirely different.
您可以混合搭配:[x**2 if x%2 == 0 else x**3 for x in range(10) if x%3 == 0]
.现在,使用if x % 3 == 0
决定要为其计算结果的x
值,并且使用if x%2 == 0
决定是否使用x**2
或x**3
作为计算结果对于那些x
.
You can mix and match: [x**2 if x%2 == 0 else x**3 for x in range(10) if x%3 == 0]
. Now if x % 3 == 0
is being used to decide which x
values to compute a result for, and if x%2 == 0
is being used to decide whether to use x**2
or x**3
as the computed result for those x
s.
这篇关于如何在python中以什么顺序评估列表推导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!