list comprehension with multiple conditions (python) -
the following code works in python
var=range(20) var_even = [0 if x%2==0 else x x in var] print var,var_even
however, thought conditions need put in end of list. if make code
var_even = [0 if x%2==0 x in var]
then won't work. there reason this?
there 2 distinct similar-looking syntaxes involved here, conditional expressions , list comprehension filter clauses.
a conditional expression of form x if y else z
. syntax isn't related list comprehensions. if want conditionally include 1 thing or different thing in list comprehension, use:
var_even = [x if x%2==0 else 'odd' x in var] # ^ "if" on here "this or that"
a list comprehension filter clause if thing
in elem x in y if thing
. part of list comprehension syntax, , goes after for
clause. if want conditionally include or not include element in list comprehension, use:
var_even = [x x in var if x%2==0] # ^ "if" on here "this or nothing"
Comments
Post a Comment