Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing array range as argument to a function?

is there a way to pass array-range as argument to function ? Something like :

> blah(ary,arg1=1:5)

def blah(ary,arg1): print ary[arg1]
like image 806
sten Avatar asked Feb 22 '15 00:02

sten


1 Answers

Python accepts the 1:5 syntax only within square brackets. The interpreter converts it into a slice object. The __getitem__ method of the object then applies the slice.

Look at numpy/lib/index_tricks.py for some functions that take advantage of this. Actually they aren't functions, but rather classes that define their own __getitem__ methods. That file may give you ideas.

But if you aren't up to that, then possibilities include:

blah(arr, slice(1, 5))
blah(arr, np.r_[1:5])

nd_grid, mgrid, ogrid extend the 'slice' concept to accept an imaginary 'step' value:

mgrid[-1:1:5j]
# array([-1. , -0.5,  0. ,  0.5,  1. ])

Just be aware that anything which expands on a slice before passing it to your blah function, won't know about the shape of the other argument. So np.r_[:-1] just returns [].

And None can be used in slice: e.g. slice(None,None,-1) is equivalent of [::-1].

like image 117
hpaulj Avatar answered Oct 21 '22 07:10

hpaulj