Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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']
like image 387
Ming Ting Avatar asked Oct 21 '25 03:10

Ming Ting


2 Answers

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']
like image 200
niemmi Avatar answered Oct 24 '25 07:10

niemmi


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.

like image 33
juanpa.arrivillaga Avatar answered Oct 24 '25 09:10

juanpa.arrivillaga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!