Python Repeat Elements in One List Based on Elements from Another
Given the following lists: a = [0, 5, 1] b = [1, 2, 1] I'd like to repeat each element of [a] by the number of its corresponding position in [b] to produce this: [0, 5, 5, 1] i.e. 0 occurs 1 time, 5 occurs 2 times, and 1 occurs 1 time. In [7]: a = [0, 5, 1] In [8]: b = [1, 2, 1] In [9]: list(itertools.chain(*(itertools.repeat(elem, n) for elem, n in zip(a, b)))) Out[9]: [0, 5, 5, 1] In [10]: b = [2, 3, 4] In [11]: list(itertools.chain(*(itertools.repeat(elem, n) for elem, n in zip(a, b)))) Out[11]: [0, 0, 5, 5, 5, 1, 1, 1, 1] The pieces here are as follows: itertools.repeat(elem, n) - repeat