Numpy 数组的切片操作

时间:2022-02-21 01:54:28

实例+解释如下(表格):关键是要明白python中数组的下标体系。一套从左往右,一套从右往左。

 

 1 import numpy as np  2 import sys  3  4 def main():  5 A=np.array([1,2,3,4,5,6,7,8,9,0])  6 B=A.copy()  7 print A  8 print 'same as print A,',A[:]  9 print 'same as print A,',A[::1] 10 print 'reverse A,',A[::-1] 11 print 'print all elements with 2 interval,',A[::2] 12 print 'print elements from the 4th element with 2 interval,',A[3::2] 13 print 'print elements from the last 4th element with 2 interval,',A[-3::2] 14 print 'print elements from the 2nd to 5th element with 2 interval,',A[1:4:2] 15 print 'reverse print all elements with 2 interval,',A[::-2] 16 print 'reverse print elements from the 4th element with 2 interval,',A[3::-2] 17 print 'reverse print elements from the last 4th element with 2 interval,',A[-3::-2] 18 #print A[a:b:c]: a and b determine range of slide. c determine the interval and direction (forth or reverse) 19 print A[:-3:-1] 20 print A[:3:1] 21 print A[:3:-1] 22 C=A[::-1] 23 C[0]=10 24 print 'A is also changed as how does c change,',A 25 B[9]=0 26 print 'A will not be affected when B change,',A 27 print 'array slide from second element to the last one,',A[1:] 28 print 'array slide from last second element to the first one,',A[:-1] 29 30 31 32 if __name__ == "__main__": 33 main()

 

A=np.array([1,2,3,4,5,6,7,8,9,0]) 1 2 3 4 5 6 7 8 9 0
下标系一Index(Left to Right) 0 1 2 3 4 5 6 7 8 9
下标系二Index(Right to Left) -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
A[a:b:c] a和b   确定:切片操作的范围(from a to b, exclude b.), C 确定具体切片的pace和方向(例如:1表示Left to Right,pace=1. -1表示Right to   Left,pace=1.)。
实例:A[:3:1] output: 1,2,3.   注:Index 3处对应的数组值4。1表示从左往右,步的大小是1。所以输出1,2,3
实例:A[:-3:-1] output:0,9   注:Index -3处对应的数组值8。-1表示从右往左,步的大小是1。所以输出0,9
实例:A[:3:-1] output:0,9,8,7,6,5   注:Index 3处对应的数组值4。-1表示从右往左,步的大小是1。所以输出0,9,8,7,6,5
实例:A[:-3:1]

output:1,2,3,4,5,6,7   注:Index -3处对应的数组值8。1表示从左往右,步的大小是1。所以输出1,2,3,4,5,6,7

实例:A[-3::-1]

output:8,7,6,5,4,3,2,1   注:Index -3处对应的数组值8。-1表示从右往左,步的大小是1。所以输出8,7,6,5,4,3,2,1