Examples + explanations are as follows (table): The key is to understand the subscript system of arrays in Python. Set from left to right, set from right to left.
0 -10
A=np.array ([1,2,3,4,5,6,7,8,9,0]) |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
0 |
subscript one index (left-to-right) | TD class= "XL65" align= "right" width= ">
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
subscript two index (right-to-left) | TD class= "XL65" align= "right" width= ">
-9 |
-8 |
-7 |
-6 |
-5 |
-4 |
-3 |
-2 |
-1 |
A[A:B:C] |
A and B determine: The range of the slice operation (from A to B, exclude B), C determines the pace and direction of the specific slice (for example: 1 indicates left to right,pace=1. -1 means right to left,pace=1.). |
Example: A[:3:1] |
output:1,2,3. Note: The corresponding array value at Index 3 is 4. 1 indicates that the size of the step is 1 from left to right. So output |
Example: A[:-3:-1] |
output:0,9 Note: The corresponding array value at INDEX-3 is 8. 1 means the size of the step is 1 from right to left. So the output 0,9 |
Example: A[:3:-1] |
output:0,9,8,7,6,5 Note: The corresponding array value at Index 3 is 4. 1 means the size of the step is 1 from right to left. So the output 0,9,8,7,6,5 |
Example: A[:-3:1] |
output:0,9 Note: The corresponding array value at INDEX-3 is 8. 1 indicates that the size of the step is 1 from left to right. So the output 1,2,3,4,5,6,7,8 |
Example: A[-3::-1] |
output:8,7,6,5,4,3,2,1 Note: The corresponding array value at INDEX-3 is 8. 1 means the size of the step is 1 from right to left. So the output 8,7,6,5,4,3,2,1 |
1 ImportNumPy as NP2 ImportSYS3 4 defMain ():5A=np.array ([1,2,3,4,5,6,7,8,9, 0])6b=a.copy ()7 PrintA8 Print 'Same as print A,', a[:]9 Print 'Same as print A,', A[::1]Ten Print 'Reverse A,', a[::-1] One Print 'Print all elements with 2 interval,', A[::2] A Print 'print elements from the 4th element with 2 interval,', A[3::2] - Print 'print elements from the last 4th element with 2 interval,', A[-3::2] - Print 'print elements from the 2nd to 5th element with 2 interval,', A[1:4:2] the Print 'reverse Print all elements with 2 interval,', a[::-2] - Print 'Reverse print elements from the 4th element with 2 interval,', a[3::-2] - Print 'Reverse print elements from the last 4th element with 2 interval,', a[-3::-2] - #print A[a:b:c]: A and b determine range of slide. C Determine the interval and direction (forth or reverse) + PrintA[:-3:-1] - PrintA[:3:1] + PrintA[:3:-1] AC=a[::-1] atc[0]=10 - Print 'A is also changed as how to does C change,', A -b[9]=0 - Print 'A won't is affected when B change,', A - Print 'array slide from second element to the last one,', a[1:] - Print 'array slide from last second element to the first one,', a[:-1] in - to + if __name__=="__main__": -Main ()
Slicing operations on Numpy arrays