Multiplying strings in a list by numbers from another list, element by element

Question:

I have two lists, ['A', 'B', 'C', 'D'] and [1, 2, 3, 4]. Both lists will always have the same number of items. I need to multiply each string by its number, so the final product I am looking for is:

['A', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'D']
Asked By: Ming Ting

||

Answers:

I would use itertools.repeat for a nice, efficient implementation:

>>> letters = ['A', 'B', 'C', 'D']
>>> numbers = [1, 2, 3, 4]
>>> import itertools
>>> result = []
>>> for letter, number in zip(letters, numbers):
...     result.extend(itertools.repeat(letter, number))
...
>>> result
['A', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'D']
>>>

I also think it is quite readable.

Answered By: juanpa.arrivillaga

The code is pretty straight forward, see inline comments

l1 = ['A', 'B', 'C', 'D'] 
l2 = [1, 2, 3, 4]
res = []
for i, x in enumerate(l1): # by enumerating you get both the item and its index
    res += x * l2[i] # add the next item to the result list
print res

OUTPUT

['A', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'D']
Answered By: Nir Alfasi

You use zip() to do it like this way:

a = ['A', 'B', 'C', 'D']
b = [1, 2, 3, 4]

final = []
for k,v in zip(a,b):
    final += [k for _ in range(v)]

print(final)

Output:

>>> ['A', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'D']

Or you can do it, too, using zip() and list comprehension:

a = ['A', 'B', 'C', 'D']
b = [1, 2, 3, 4]
final = [k for k,v in zip(a,b) for _ in range(v)]
print(final)

Output:

>>> ['A', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'D']
Answered By: Chiheb Nexus

Nested list comprehension works too:

>>> l1 = ['A', 'B', 'C', 'D'] 
>>> l2 = [1, 2, 3, 4]
>>> [c for c, i in zip(l1, l2) for _ in range(i)]
['A', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'D']

In above zip returns (char, count) tuples:

>>> t = list(zip(l1, l2))
>>> t
[('A', 1), ('B', 2), ('C', 3), ('D', 4)]

Then for every tuple the second for loop is executed count times to add the character to the result:

>>> [char for char, count in t for _ in range(count)]
['A', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'D']
Answered By: niemmi

You can use NumPy and then convert the NumPy array to a list:

letters = ['A', 'B', 'C', 'D']
times = [1, 2, 3, 4]
np.repeat(letters, times).tolist()

#output

['A', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'D']
Answered By: Phoenix
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.