Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variable to indicate index range [duplicate]

I want to create a list containing indices that would be used to get elements from another list.

A simple case:

A = [5,6,7,8,9,10]    
b = 2:4  

I want to then do something like

C = A[b]

Which would be like saying C = A[2:4]

I want to later extend this to multidimensional arrays, where e.g b = [2:4, 5:6] and I can simply call A[b] to extract a multidimensional array out of A.

like image 291
BarkingCat Avatar asked Feb 07 '18 10:02

BarkingCat


2 Answers

You can define b as a slice object to achieve this:

In[9]:
A = [5,6,7,8,9,10]    
b = slice(2,4)
A[b]

Out[9]: [7, 8]

Regarding your other requirement I think if you create a list object containing 2 slice objects then it should achieve what you want:

In[18]:
import numpy as np
a = np.arange(100).reshape(10,10)
b = [slice(1,3), slice(3,4)]
a[b]

Out[18]: 
array([[13],
       [23]])
like image 197
EdChum Avatar answered Oct 01 '22 13:10

EdChum


You can either use straight python using e.g. slice:

>>> A = [5,6,7,8,9,10]    
>>> b = slice(2,4)
>>> A[b]
[7, 8]

But this does not scale very well to nd-arrays. To do this, I'd recommend using numpy's np.s_ function which does exactly what you are looking for, without the need of explicitly constructing a slice for each axis.

>>> b = np.s_[2:4]
>>> A[b]
[7, 8]

This extends nicely to e.g. 2d arrays:

>>> A = np.ones(10, 10)
>>> b = np.s_[2:4, 5:6]
>>> A[b]
array([[ 1.],
       [ 1.]])
like image 37
Jonas Adler Avatar answered Oct 01 '22 15:10

Jonas Adler