I want to multiply a * b
:
a = ['a', 'e', 'y']
b = [3, 2, 1]
and get:
c = ['a', 'a', 'a', 'e', 'e', 'y']
I want to multiply a * b
:
a = ['a', 'e', 'y']
b = [3, 2, 1]
and get:
c = ['a', 'a', 'a', 'e', 'e', 'y']
That can be done with sum()
, zip()
and a list comprehension like:
c = sum([[s] * n for s, n in zip(a, b)], [])
a = ['a', 'e', 'y']
b = [3, 2, 1]
c = sum([[s] * n for s, n in zip(a, b)], [])
print(c)
['a', 'a', 'a', 'e', 'e', 'y']
zip()
is your friend here:
a = ['a', 'e', 'y']
b = [3, 2, 1]
c = []
for x, y in zip(a, b):
c.extend([x] * y)
print(c)
# ['a', 'a', 'a', 'e', 'e', 'y']
Or with itertools.chain.from_iterable()
:
from itertools import chain
c = list(chain.from_iterable([x] * y for x, y in zip(a, b)))
print(c)
# ['a', 'a', 'a', 'e', 'e', 'y']
You can try this:
a = ['a', 'e', 'y']
b = [3, 2, 1]
new_list = [i for b in [[c]*d for c, d in zip(a, b)] for i in b]
Output:
['a', 'a', 'a', 'e', 'e', 'y']
The most basic loop approach would be this, in my opinion:
a = ['a', 'e', 'y']
b = [3, 2, 1]
c = []
for i in range(len(a)):
c.extend(list(a[i]*b[i]))
Fancy one liner:
>>> from itertools import chain
>>> a = ['a', 'e', 'y']
>>> b = [3, 2, 1]
>>> c = list(chain(*[x*y for x,y in zip(a,b)]))
>>> c
['a', 'a', 'a', 'e', 'e', 'y']
You don't actually need to import any modules, as I said in the comments, please consider reading the Python docs.
a = ['a', 'e', 'y']
b = [3, 2, 1]
c = []
for i in range(len(a)):
c += [a[i]] * b[i]
print(c)
Through collections.Counter you can do this:-
Try this:-
from collections import Counter
a = ['a', 'e', 'y']
b = [3, 2, 1]
d = {x:y for x,y in zip(a,b)}
c = Counter(d)
print(list(c.elements())) #your output