I want to multiply a * b:
a = ['a', 'e', 'y'] b = [3, 2, 1]and get:
c = ['a', 'a', 'a', 'e', 'e', 'y']
Stephen Rauch♦
45.7k30 gold badges105 silver badges126 bronze badges
asked Feb 17, 2018 at 2:11
5
That can be done with sum(), zip() and a list comprehension like:
Code:
c = sum([[s] * n for s, n in zip(a, b)], [])Test Code:
a = ['a', 'e', 'y'] b = [3, 2, 1] c = sum([[s] * n for s, n in zip(a, b)], []) print(c)Result:
['a', 'a', 'a', 'e', 'e', 'y']answered Feb 17, 2018 at 2:14
Stephen Rauch♦Stephen Rauch
45.7k30 gold badges105 silver badges126 bronze badges
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']answered Feb 17, 2018 at 2:15
RoadRunnerRoadRunner
24.9k6 gold badges36 silver badges72 bronze badges
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']answered Feb 17, 2018 at 2:29
Ajax1234Ajax1234
67.4k7 gold badges58 silver badges99 bronze badges
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]))answered Feb 17, 2018 at 2:32
FatihAkiciFatihAkici
4,2911 gold badge28 silver badges47 bronze badges
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']answered Feb 17, 2018 at 2:22
mshsayemmshsayem
17.2k11 gold badges61 silver badges67 bronze badges
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)answered Feb 17, 2018 at 3:05
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 outputanswered Feb 17, 2018 at 3:57
NarendraNarendra
1,5651 gold badge9 silver badges20 bronze badges