Passing an array as an argument to a function?

Is there a way to pass an array-range as an argument to a function? Sort of:

> blah(ary,arg1=1:5)

def blah(ary,arg1): print ary[arg1]
+4
source share
3 answers

Python 1:5only accepts syntax in square brackets. The interpreter converts it to an object slice. Then the __getitem__object method applies the slice.

Look at numpy/lib/index_tricks.pyfor some features that use this. These are actually not functions, but classes that define their own methods __getitem__. This file may give you ideas.

But if you can’t handle it, then features include:

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

nd_grid, mgrid, ogrid "", "":

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

, , blah, . np.r_[:-1] [].

None slice: . slice(None,None,-1) [::-1].

+5

slice

>>> def blah(ary,arg1):
...     print ary[arg1]
>>> blah(range(10), slice(1, 5))
[1, 2, 3, 4]
+4

you can try the following:

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]
0
source

All Articles