Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range with repeated consecutive numbers

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?

like image 702
miku Avatar asked Jun 12 '18 09:06

miku


People also ask

How do you repeat a number in a series in Python?

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.


2 Answers

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]
like image 173
Mihai Alexandru-Ionut Avatar answered Sep 21 '22 02:09

Mihai Alexandru-Ionut


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)
like image 43
jpp Avatar answered Sep 19 '22 02:09

jpp