不一致的理解语法? [英] Inconsistent comprehension syntax?
问题描述
我只是偶然发现了 python 语法中的一个缺陷——否则我遗漏了一些东西.
I just stumbled over what seems to be a flaw in the python syntax-- or else I'm missing something.
看到这个:
[x for x in range(30) if x % 2 == 0]
但这是一个语法错误:
[x for x in range(30) if x % 2 == 0 else 5]
如果你有一个 else
子句,你必须写:
If you have an else
clause, you have to write:
[x if x % 2 == 0 else 5 for x in range (30)]
但这是一个语法错误:
[x if x %2 == 0 for x in range(30)]
我错过了什么?为什么这么不一致?
What am I missing? Why is this so inconsistent?
推荐答案
你在这里混合语法.这里有两个不同的概念:
You are mixing syntax here. There are two different concepts at play here:
列表理解语法.这里
if
充当过滤器;是否在迭代中包含一个值.没有else
,因为这已经是不包含"的情况了.
List comprehension syntax. Here
if
acts as a filter; include a value in the iteration or not. There is noelse
, as that is the 'don't include' case already.
条件表达式.这必须始终返回一个值,即真"或假"表达式的结果.
A conditional expression. This must always return a value, either the outcome of the 'true' or the 'false' expression.
记住:列表推导式从循环中产生一系列值.通过使用 if
,您可以控制将输入迭代中的元素用于输出的数量.
Remember: list comprehensions produce a sequence of values from a loop. By using if
you can control how many elements from the input iterable are used for the output.
条件表达式另一方面,与任何其他表达式一样:一个表达式总是产生一个结果;条件表达式可让您在两种可能的结果之间进行选择.但是因为它必须产生一个结果,所以你不能在没有 else
部分的情况下编写一个.
A conditional expression on the other hand, works like any other expression: an expression always produces a single result; the conditional expression lets you pick between two possible outcomes. But because it must produce a result you can’t write one without the else
part.
请注意,表达式可以并且经常嵌套.条件表达式本身包含三个子表达式:
Note that expressions can and are frequently nested. The conditional expression itself contains three sub-expressions:
expr1 if expr2 else expr3
# ^ ^
# used when expr2 |
# is true |
# /
# used when expr2 is
# false
列表推导式也包含子表达式.开头的那个(for <target> in <iterable>
部分之前)是每次迭代执行以生成输出列表中的值的子表达式.迭代器表达式(在 in
之后)是另一个.可选的 if
过滤器也采用表达式.如果您愿意,您可以在任何这些地方使用条件表达式.但是,这并不意味着您可以在没有条件表达式语法的其他部分的情况下向列表推导式中添加额外的 else
.
List comprehension also contain sub-expressions. The one at the start (before the for <target> in <iterable>
part) is the sub-expression that is executed each iteration to produce the value in the output list. The iterator expression (after in
) is another. The optional if
filter takes an expression too. In any of these places you could use a conditional expression if you so choose. But, that doesn’t mean you can add an extra else
to the list comprehension without the other parts of the conditional expression syntax.
这篇关于不一致的理解语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!