Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

list comprehension with multiple conditions (python)

The following code works in Python

var=range(20)
var_even = [0 if x%2==0 else x for x in var]
print var,var_even

However, I thought that the conditions need to be put in the end of a list. If I make the code

var_even = [0 if x%2==0 for x in var]

Then it won't work. Is there a reason for this?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

There are two distinct but similar-looking syntaxes involved here, conditional expressions and list comprehension filter clauses.

A conditional expression is of the form x if y else z. This syntax isn't related to list comprehensions. If you want to conditionally include one thing or a different thing in a list comprehension, this is what you would use:

var_even = [x if x%2==0 else 'odd' for x in var]
#             ^ "if" over here for "this or that"

A list comprehension filter clause is the if thing in elem for x in y if thing. This is part of the list comprehension syntax, and it goes after the for clause. If you want to conditionally include or not include an element in a list comprehension, this is what you would use:

var_even = [x for x in var if x%2==0]
#                          ^ "if" over here for "this or nothing"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...