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

  • 本文关键字:列表 复制 python list
  • 更新时间 :
  • 英文 :

list1 = ['Name1', 'Name2', 'Name3']
list2 = [1, 3, 2]

预期的结果:

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

根据另一个列表的相应元素位置查找列表中的重复项。如果你能帮助我,那就太好了,谢谢。

使用下面的列表推导式+zip:

list1 = ['Name1', 'Name2', 'Name3']
list2 = [1, 3, 2]
res = [e1 for e1, e2 in zip(list1, list2) for _ in range(e2)]
print(res)

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

Withchainandrepeatfrom itertools:

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

短版:

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

上网试试!

最新更新