Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

python - Inconsistent comprehension syntax?

I just stumbled over what seems to be a flaw in the python syntax-- or else I'm missing something.

See this:

[x for x in range(30) if x % 2 == 0]

But this is a syntax error:

[x for x in range(30) if x % 2 == 0 else 5]

If you have an else clause, you have to write:

[x if x % 2 == 0 else 5 for x in range (30)]

But this is a syntax error:

[x if x %2 == 0 for x in range(30)]

What am I missing? Why is this so inconsistent?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are mixing syntax here. There are two different concepts at play here:

  • List comprehension syntax. Here if acts as a filter; include a value in the iteration or not. There is no else, 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.

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.

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...