Skip to content Skip to sidebar Skip to footer

How To Multiply A List Of Text By A List Of Integers And Get One Long List Of Text?

This is for Python 3. I have two lists: lista = ['foo', 'bar'] listb = [2, 3] I'm trying to get: newlist = ['foo', 'foo', 'bar', 'bar', 'bar'] But I'm stuck. If I try: new_list =

Solution 1:

You can use list comprehension with the following one liner:

new_list = [x for n,x in zip(listb,lista) for _ in range(n)]

The code works as follows: first we generate a zip(listb,lista) which generates tuples of (2,'foo'), (3,'bar'), ... Now for each of these tuples we have a second for loop that iterates n times (for _ in range(n)) and thus we add x that many times to the list.

The _ is a variable that is usually used to denote that the value _ carries is not important: it is only used because we need a variable in the for loop to force iteration.

Solution 2:

You were pretty close yourself! All you needed to do was use list.extend instead of list.append:

new_list = []
for i in zip(lista, listb):
    new_list.extend([i[0]] * i[1])

this extends the list new_list with the elements you supply (appends each individual element) instead of appending the full list.

If you need to get fancy you could always use functions from itertools to achieve the same effect:

from itertools import chain, repeat

new_list = list(chain(*map(repeat, lista, listb)))

.extend in a loop, though slower, beats the previous in readability.

Solution 3:

Use .extend() rather than .append().

Post a Comment for "How To Multiply A List Of Text By A List Of Integers And Get One Long List Of Text?"