I have
list = [a, b, c, d]
and
numbers = [2, 4, 3, 1]
I want to get a list of the type of:
new_list = [a, a, b, b, b, b, c, c, c, d]
This is what I have so far:
new_list=[]
for i in numbers: for x in list: for i in range(1,i+1): new_list.append(x)
Here's one way to do it using zip
, string multiplication and a list comprehension:
lst = ['a', 'b', 'c', 'd']
numbers = [2 , 4, 3, 1]r = [x for i, j in zip(lst, numbers) for x in i*j]
print(r)
# ['a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd']
Pay attention to the choice of names when using Python. A name like list
renders the builtin list function unusable.
If the items in lst
are not strings you can simply use a nested comprehension on range
, to duplicate the items in the list.