也许这之前被问过,在这种情况下我会删除这个问题,但我有两个列表:
occurence_list = [1, 2, 3, 4, 5]
value_list = [10, 20, 30, 40, 50]
我希望每个值与其他列表中相同索引的值显示的次数相同:
result = [10, 20, 20, 30, 30, 30, 40, 40, 40, 40, 50, 50, 50, 50, 50]
如何做到这一点?
答案 0 :(得分:5)
使用itertools.repeat()
和chain()
:
In [6]: from itertools import repeat, chain
In [7]: list(chain.from_iterable(repeat(i, j) for i, j in zip(value_list, occurence_list)))
Out[7]: [10, 20, 20, 30, 30, 30, 40, 40, 40, 40, 50, 50, 50, 50, 50]
不是通过chain.from_iterable
连接重复对象,然后将结果转换为列表,也可以使用嵌套列表解析:
In [12]: [t for i, j in zip(value_list, occurence_list) for t in repeat(i, j)]
Out[12]: [10, 20, 20, 30, 30, 30, 40, 40, 40, 40, 50, 50, 50, 50, 50]
答案 1 :(得分:1)
使用list comprehension
,
In [7]: [j for i,j in enumerate(value_list) for _ in range(occurence_list[i])]
Out[7]: [10, 20, 20, 30, 30, 30, 40, 40, 40, 40, 50, 50, 50, 50, 50]