Say we have the list a = [3,4,2,1], from a we want to obtain the following array: b = [0,0,0,1,1,1,1,2,2,3].
I have managed to do it like this:
import numpy as np
a = [3,4,2,1]
b = np.concatenate([[i] * n for i, n in enumerate(a])
print(b)
Output:
array([0, 0, 0, 1, 1, 1, 1, 2, 2, 3])
Which works fine, but I can’t help but wonder if there is a better way?
>Solution :
Try np.repeat: np.repeat([0,1,2,3], [3,4,2,1])