list1 = ['Name1', 'Name2', 'Name3']
list2 = [1, 3, 2]
desired result:
['Name1', 'Name2', 'Name2', 'Name2', 'Name3', 'Name3']
Looking to duplicate items in a list based on the corresponding element position of a different list. Any help would be great, thank you.
CodePudding user response:
Use the following list comprehension zip
:
list1 = ['Name1', 'Name2', 'Name3']
list2 = [1, 3, 2]
res = [e1 for e1, e2 in zip(list1, list2) for _ in range(e2)]
print(res)
Output
['Name1', 'Name2', 'Name2', 'Name2', 'Name3', 'Name3']
CodePudding user response:
With chain
and repeat
from itertools:
res = list(chain.from_iterable(map(repeat, list1, list2)))
Short version:
res = [*chain(*map(repeat, list1, list2))]