I would like to create a range (e.g. (1, 5)) of numbers with some repetitions (e.g. 4):
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]
One way would be to write:
list(itertools.chain(*([x] * 4 for x in range(1, 5))))
Or similarly:
list(itertools.chain(*(itertools.repeat(x, 4) for x in range(1, 5))))
However, there is a flatting step, which could be avoided.
Is there a more pythonic or more compact version to generate such a sequence?
repeat() function repeat elements of a Series. It returns a new Series where each element of the current Series is repeated consecutively a given number of times. Parameter : repeats : The number of repetitions for each element.
You can just use a list comprehension instead.
l = [i for i in range(1, 5) for _ in range(4)]
Output
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]
Nothing wrong with your solution. But you can use chain.from_iterable
to avoid the unpacking step.
Otherwise, my only other recommendation is NumPy, if you are happy to use a 3rd party library.
from itertools import chain, repeat
import numpy as np
# list solution
res = list(chain.from_iterable(repeat(i, 4) for i in range(1, 5)))
# NumPy solution
arr = np.repeat(np.arange(1, 5), 4)
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