Home > Software design >  Python list comprehension : build a list from 2 lists
Python list comprehension : build a list from 2 lists

Time:04-01

This code

colors = ["#F1A141", "#52D987", "#12A3FF", "#FF3F94", "#564DA6"]
skills = [3, 4, 4, 2, 3]
palette = [(item for i in range(skills[index])) for (index, item) in enumerate(colors)]

returns no error but buggy list items

[<generator object <listcomp>.<genexpr> at 0x7f302eac9650>, <generator object <listcomp>.<genexpr> at 0x7f302eac9550>, ... ]

Where's my mistake ?

Edit : the expected output is a list with 3 "#F1A141" items followed by 4 "#52D987" items, etc.

CodePudding user response:

This is a generator expression: (item for i in range(skills[index]) if you want a list of lists, you need to use [] inside the comprehension.

Given your desired output, it might be simpler to zip the two lists and avoid the range. Then nest the comprehension to flatten it:

colors = ["#F1A141", "#52D987", "#12A3FF", "#FF3F94", "#564DA6"]
skills = [3, 4, 4, 2, 3]

[c for color, n in zip(colors, skills) for c in [color] * n]

Produces:

['#F1A141',
 '#F1A141',
 '#F1A141',
 '#52D987',
 '#52D987',
 '#52D987',
 '#52D987',
 '#12A3FF',
 '#12A3FF',
 '#12A3FF',
 '#12A3FF',
 '#FF3F94',
 '#FF3F94',
 '#564DA6',
 '#564DA6',
 '#564DA6']
  • Related