Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat each elements based on a list of values

Tags:

python

list

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?

like image 777
kentwait Avatar asked Feb 15 '26 06:02

kentwait


2 Answers

Just use a simple list comprehension:

>>> x = ['A', 'B', 'C']
>>> y = [2, 1, 3]
>>> [x[i] for i in range(len(x)) for j in range(y[i])]
['A', 'A', 'B', 'C', 'C', 'C']
>>> 
like image 125
A.J. Uppal Avatar answered Feb 16 '26 21:02

A.J. Uppal


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']
like image 22
Paul Rooney Avatar answered Feb 16 '26 22:02

Paul Rooney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!