Search code examples
pythonnumpysample

Is there a pythonic way to sample N consecutive elements from a list or numpy array


Is there a pythonic way to select N consecutive elements from a list or numpy array.

So Suppose:

Choice = [1,2,3,4,5,6] 

I would like to create a new list of length N by randomly selecting element X in Choice along with the N-1 consecutive elements following choice.

So if:

X = 4 
N = 4

The resulting list would be:

Selection = [5,6,1,2] 

I think something similar to the following would work.

S = [] 
for i in range(X,X+N):
    S.append(Selection[i%6])    

But I was wondering if there is a python or numpy function that can select the elements at once that was more efficient.


Solution

  • Use itertools, specifically islice and cycle.

    start = random.randint(0, len(Choice) - 1)
    list(islice(cycle(Choice), start, start + n))
    

    cycle(Choice) is an infinite sequence that repeats your original list, so that the slice start:start + n will wrap if necessary.