Home > Software engineering >  Is it possible to get 3 elements in a string/list/array, the first two being consecutive and the thi
Is it possible to get 3 elements in a string/list/array, the first two being consecutive and the thi

Time:07-12

Given the array:

import numpy as np
arr = np.array(range(10))
print(arr)
[0,1,2,3,4,5,6,7,8,9]

is it possible to get in one single slice ex. arr[1:6:1] the numbers [1, 2, 5]?

I've tried everything, from steps to multiple slicing, it seems I cannot get past the uneven step between the numbers. I'm pretty sure it's not possible, but if it is, I'd like to hear it since I wasted a few hours on this.

Thanks in advance.

CodePudding user response:

In numpy, you can directly pass a list of indeces instead of a slice object:

arr[[1, 2, 5]]

If there is an underlying pattern to those indeces you can use it to create the index list.

  • Related