kentwait kentwait - 4 months ago 9
Python Question

Repeat each elements based on a list of values

Is there a Python builtin that repeats each element of a list based on the corresponding value in another list? For example

A
in list
x
position 0 is repeated 2 times because of the value
2
at position 0 in the list
y
.

>>> x = ['A', 'B', 'C']
>>> y = [2, 1, 3]
>>> f(x, y)
['A', 'A', 'B', 'C', 'C', 'C']


Or to put it another way, what is the fastest way to achieve this operation?

Answer

One way would be the following

x = ['A', 'B', 'C']
y = [2, 1, 3]

s = []
for a, b in zip(x, y):
    s.extend([a] * b)

print(s)

result

['A', 'A', 'B', 'C', 'C', 'C']
Comments