Multiple list comprehension in a single list comprehension

I am trying to change the values ​​of a list using a list comprehension. I can do this using 3 concept lists

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 using the below code a syntax error occurs

clr = ["green"  if i== 1 else "yellow"  if i==2 else "black"  if i == 3 for i in clr]

      

Is there a better way to do this?

+3


source to share


3 answers


Yes. You can, for example, define a dictionary :

the_dic = { 1 : 'green', 2 : 'yellow', 3 : 'black' }

      

and then do the matching like:

clr = [the_dic.get(i,i) for i in clr]
      

Or using map(..)

(in works like a generator (thus lazy):



clr = map(the_dic.get,clr)
      

Insert None

if item at is clr

not in the dictionary.

So this will add i

to the list clr

if it is not in the dictionary. This is because we are using the_dic.get(i,i)

. The first i

is the key we are looking at in the dictionary. The second i

is the "fallback" value: the value we return in case the key is not found.

If you want to filter these , you can use:

clr = [the_dic[i] for i in clr if i in the_dic]
      

+4


source


    colors = collections.defaultdict(int,{ 1:'green', 2:'yellow', 3:'black' })
    clr = [ colors[i] for i in clr ]

      



You can add if 1 <= i <= 3 condition

to list comprehension if it is important not to put an extraneous 0 in the output. In this case, you can use normal dict instead of defaultdict.

0


source


You can actually do this in a list comprehension:

[("green"  if i == 1 else ("yellow" if i == 2 else "black")) for i in clr]

      

and if you want to skip values ​​that are neither 1, 2, nor 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 the following:

[("green"  if i == 1 else ("yellow" if i == 2 else ("black" if i == 3 else i))) for i in clr]

      

0


source







All Articles