I am trying to work with the following code:
color= ['red' if House =="20" "blue" elif House =="21" "yellow" elif House =="22" else 'green' for H in House]
It gives the following error: SyntaxError: invalid syntax
Any suggestion-Idea?
I am trying to work with the following code:
color= ['red' if House =="20" "blue" elif House =="21" "yellow" elif House =="22" else 'green' for H in House]
It gives the following error: SyntaxError: invalid syntax
Any suggestion-Idea?
elif
can't be used in list comprehension. It should be else <value> if <condition>
. Applying to your code:
color= ['red' if H=="20" else "blue" if H =="21" else "yellow" if H =="22" else 'green' for H in House]
Note you are iterating over H
, not over House
update:
The general syntax look like:
[<value> if <condition> else <value> if <condition> else <value>]
This can be split into three parts:
<value> if <condition>
This corresponds to if <condition>: <value>
else <value> if <condition>
This corresponds to elif <condition>: <value>
else <value>
This corresponds to else: <value>
It would be easier to read if you use a dictionary:
colour_map = {
'20': 'red',
'21': 'blue',
'22': 'yellow',
}
color= ['green' if H not in colour_map.keys() else colour_map[H] for H in House]