Reputation: 23
Being new to python, here is my problem. Given two lists:
a = [3, 4]
b = [5, 2]
I want to create a new list which consists of items of first list repeated n number of times, where n is the corresponding element in second list. So I would like an output like:
c = [3,3,3,3,3,4,4]
Where 3 is repeated 5 times, 4 is repeated 2 times and so on. My current code looks like this
for item,no in zip(a,b):
print(str(item)*no)
which gets me:
33333
44
I am trying to figure out how to get from my current stage to the output that I want. Any help would be appreciated.
I was also thinking that maybe this could be done with list comprehension but I could not come up with the python code for it.
Upvotes: 2
Views: 842
Reputation: 76
You said you were new to Python, so here's a simple way to do it, just using basic loops:
a = [3 , 4]
b = [5 , 2]
c = []
index = 0
for i in a:
for i in range(0 , b[index]):
c.append(i)
index += 1
Upvotes: 0
Reputation: 421
Something a bit different
c = [a[b.index(j)] for i,j in enumerate(b) for i in range(j)]
Upvotes: 0
Reputation: 1
c = []
for i in range(len(b)):
for j in range(b[i]):
c.append(a[i])
print c
Upvotes: 0
Reputation: 19806
You can use list comprehension like this:
[i for i,j in zip(a, b) for k in range(j)]
The above line is equivalent to the following nested for loops:
c = []
for i,j in zip(a, b):
for k in range(j):
c.append(i)
Output:
>>> a = [3, 4]
>>> b = [5, 2]
>>> c = [i for i,j in zip(a, b) for k in range(j)]
>>> c
[3, 3, 3, 3, 3, 4, 4]
Upvotes: 0
Reputation: 30258
A simple list comprehension would work:
>>> a = [3, 4]
>>> b = [5, 2]
>>> [c for n, m in zip(a, b) for c in [n]*m]
[3, 3, 3, 3, 3, 4, 4]
If you are concerned on the memory efficiency (e.g. for large m
) then you can use itertools.repeat()
to avoid the intermediate lists:
>>> import itertools as it
>>> [c for n, m in zip(a, b) for c in it.repeat(n, m)]
[3, 3, 3, 3, 3, 4, 4]
Upvotes: 2
Reputation: 3895
You just need to use extend
c = []
for item, no in zip(a, b):
c.extend([item] * no)
Upvotes: 0
Reputation: 17041
c=[]
for item, count in zip(a,b):
c.extend([item]*count)
print(c)
should do it. Add to the list one element at a time, and then print all at once at the end. [item]*count
is a count
-element list([]
) of item
, and extend
adds the contents of the list you provide to the list you call extend
on.
Upvotes: 0