Reputation: 421
I am trying to change the values of a list using list comprehension I can do that by using 3 list comprehensions
clr = [1,2,2,1,3,1,2,3]
clr= ["green" if i== 1 else i for i in clr]
clr = ["yellow" if i==2 else i for i in clr]
clr = ["black" if i == 3 else i for i in clr]
where as using the below mentioned code is throwing syntax error
clr = ["green" if i== 1 else "yellow" if i==2 else "black" if i == 3 for i in clr]
Is there any better way to do it??
Upvotes: 3
Views: 415
Reputation: 477684
Yes. You can for instance define a dictionary:
the_dic = { 1 : 'green', 2 : 'yellow', 3 : 'black' }
and then perform a mapping like:
clr = [the_dic.get(i,i) for i in clr]
Or by using map(..)
(in python-3.x this works as a generator (thus lazily):
clr = map(the_dic.get,clr)
This will insert None
s in case the element in clr
is not in the dictionary.
This will thus add i
to the clr
list, if it is not in the dictionary. This is beause we use the_dic.get(i,i)
. The first i
is the key we lookup in the dictionary. The second i
is the "fallback" value: the value we return in case the key is not found.
In case you want to filter these out, you can use:
clr = [the_dic[i] for i in clr if i in the_dic]
Upvotes: 4
Reputation: 8388
You can actually do this within list comprehension:
[("green" if i == 1 else ("yellow" if i == 2 else "black")) for i in clr]
and if you want to skip over values that are neither 1, 2, or 3:
[("green" if i == 1 else ("yellow" if i == 2 else "black")) for i in clr if i in range(1, 4)]
and if you want to leave the values not in [1, 2, 3] unchanged do this:
[("green" if i == 1 else ("yellow" if i == 2 else ("black" if i == 3 else i))) for i in clr]
Upvotes: 0
Reputation: 475
colors = collections.defaultdict(int,{ 1:'green', 2:'yellow', 3:'black' })
clr = [ colors[i] for i in clr ]
You could add if 1 <= i <= 3 condition
to the list comprehension if it is important not to put the extraneous 0's in the output. In that case you could use an ordinary dict instead of a defaultdict.
Upvotes: 0