Reputation: 305
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.
Upvotes: 0
Views: 34
Reputation: 10165
With chain
and repeat
from itertools:
res = list(chain.from_iterable(map(repeat, list1, list2)))
Short version:
res = [*chain(*map(repeat, list1, list2))]
Upvotes: 0
Reputation: 61910
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']
Upvotes: 1