Problem with list slicing syntax in python

The extended indexing syntax is mentioned in the python document.

slice([start], stop[, step]) 

Slice objects are also generated using the advanced indexing syntax. For example: a[start:stop:step] or a[start:stop, i] . See itertools.islice() for an alternative version that returns an iterator.

a[start:stop:step] works as described. But what about the second? How is it used?

+7
python syntax slice
source share
2 answers

a[start:stop,i] calls the a.__getitem__((slice(start,stop,None), i)) method.

This raises a TypeError if a is a list, but it is a correct and useful notation if a is an empty array. In fact, I believe that Numpy developers asked Python developers to accurately extend the actual Python slice notation to make it easier to implement array slice notation.

For example,

 import numpy as np arr=np.arange(12).reshape(4,3) print(arr) # [[ 0 1 2] # [ 3 4 5] # [ 6 7 8] # [ 9 10 11]] 

1:3 selects rows 1 and 2, and 2 selects the third column:

 print(arr[1:3,2]) # [5 8] 

PS. To experiment with which snippet is sent to __getitem__ , you can play __getitem__ with this toy code:

 class Foo(list): def __getitem__(self,key): return repr(key) foo=Foo(range(10)) print(foo[1:5,1,2]) # (slice(1, 5, None), 1, 2) 
+11
source share

The notation [:,:] used to slice multidimensional arrays . Python does not have multidimensional arrays by default, but the syntax supports it and numpy , for example, uses this syntax.

+4
source share

All Articles