Given the following lists:
a = [0, 5, 1]
b = [1, 2, 1]
I'd like to repeat each element of [a] by the number of its corresponding position in [b] to produce this:
[0, 5, 5, 1]
i.e. 0 occurs 1 time, 5 occurs 2 times, and 1 occurs 1 time.
Using the * Operator The * operator can also be used to repeat elements of a list. When we multiply a list with any number using the * operator, it repeats the elements of the given list.
Lists can be created using the repetition operator, *. We are accustomed to using the * symbol to represent multiplication, but when the operand on the left side of the * is a list, it becomes the repetition operator. The repetition operator makes multiple copies of a list and joins them all together.
To check if a list contains any elements of another list: Use a generator expression to iterate over the list. Check if any elements in the first list are contained in the second list. The any() method will return True if the list contains any elements of the other list.
How do you create an n list length in Python? To create a list of n placeholder elements, multiply the list of a single placeholder element with n . For example, use [None] * 5 to create a list [None, None, None, None, None] with five elements None . You can then overwrite some elements with index assignments.
In [7]: a = [0, 5, 1]
In [8]: b = [1, 2, 1]
In [9]: list(itertools.chain(*(itertools.repeat(elem, n) for elem, n in zip(a, b))))
Out[9]: [0, 5, 5, 1]
In [10]: b = [2, 3, 4]
In [11]: list(itertools.chain(*(itertools.repeat(elem, n) for elem, n in zip(a, b))))
Out[11]: [0, 0, 5, 5, 5, 1, 1, 1, 1]
The pieces here are as follows:
itertools.repeat(elem, n)
- repeat elem n timeszip(a, b)
Make a list of 2-tuples out of the two lists, pairing each element with the corresponding element in the other list. This gives you exactly what you need to pass to itertools.repeat
in your use case.itertools.chain
- flattens the resulting list of iterators into a single list of values. You can either chain(*iterable)
as I have done or chain.from_iterable(iterable)
as Martijn Peters does.Use the zip()
function with itertools.repeat()
and itertools.chain.from_iterable()
:
try:
# use iterator zip on Python 2 too
from future_builtins import zip
except ImportError:
pass
from itertools import repeat, chain
list(chain.from_iterable(repeat(value, count) for value, count in zip(a, b)))
(I added a Python 2 forward-compatible import for those that can't switch to Python 3 yet).
Demo:
>>> from itertools import repeat, chain
>>> a = [0, 5, 1]
>>> b = [1, 2, 1]
>>> list(chain.from_iterable(repeat(value, count) for value, count in zip(a, b)))
[0, 5, 5, 1]
An alternative approach would be to use a list comprehension; this is slower as repeating elements is done in bytecode instead of C:
[value for value, count in zip(a, b) for _ in range(count)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With