Passing array range as argument to a function?
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]
.
you can try like this:
def blah(ary, arg):
arg = map(int, arg.split(":"))
print ary[arg[0]:arg[1]]
blah([1,2,3,4,5,6],"2:5")
output:
[3, 4, 5]
You can use the slice function
>>> def blah(ary,arg1):
... print ary[arg1]
>>> blah(range(10), slice(1, 5))
[1, 2, 3, 4]