简体   繁体   English

根据不同列表的值复制列表中的项目

[英]Duplicating Items in list based on value of a different list

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.希望根据不同列表的相应元素 position 复制列表中的项目。 Any help would be great, thank you.任何帮助都会很棒,谢谢。

Use the following list comprehension + zip :使用以下列表理解+ 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 Output

['Name1', 'Name2', 'Name2', 'Name2', 'Name3', 'Name3']

With chain and repeat from itertools :使用chain并从itertools repeat

res = list(chain.from_iterable(map(repeat, list1, list2)))

Short version:简洁版本:

res = [*chain(*map(repeat, list1, list2))]

Try it online! 在线试用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM