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]
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]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With