注意:
a[::-2] :切片起始索引和终止索引省略,-2表示逆序步长为2;
a[-4::-2] :起始索引逆序第4个,终止索引为0,逆序步长为2;
a[2::3] :起始索引为2,终止索引为最后一个,正序步长为3;
b[…,1] D0和D1不作约束,D2切片index=1的数据
注:{axis=0:’D0’,axis=1:’D1’, axis=2:’D2’ }
切片code如下:
一维数组:
import os
import sys
import numpy as np
def main (argc, argv, envp):
a = np.arange(1,20,2)
print('shape:', a.shape) # (10,) a:[ 1 3 5 7 9 11 13 15 17 19]
print('1):',a[:3]) # 索引0,1,2
print('2):', a[1:6]) # 索引1~5,不包含索引6
print('3):', a[5:]) # 索引5及其之后的所有索引
print('4):', a[:-3]) # 索引0~索引6(逆序第3个索引之前的索引)
print('5):', a[::-1]) # 所有索引逆序,起始和终止索引省略表示,-1表示逆序步长为1
print('6):', a[::-2]) # 所有索引逆序,起始和终止索引省略表示,-2表示逆序步长为2
return 0
if __name__ == '__main__':
sys.exit(main(len(sys.argv), sys.argv, os.environ))
output:
shape: (10,)
1): [1 3 5]
2): [ 3 5 7 9 11]
3): [11 13 15 17 19]
4): [ 1 3 5 7 9 11 13]
5): [19 17 15 13 11 9 7 5 3 1]
6): [19 15 11 7 3]
[Finished in 1.4s]
多维数组:
import os
import sys
import numpy as np
def main (argc, argv, envp):
b = np.arange(1,25).reshape(2,3,4)
print('b:','\n',b,'\n') # {axis=0:'D0',axis=1:'D1', axis=2:'D2'}
print('1)', b[:,0,0],'\n') # D0不做约束,D1和D2切片index=0的数据
print('2)', b[0,:,:],'\n') # 切片D0中index=0的数据,D1和D2不作约束
print('3)', b[...,1],'\n') # D0和D1不作约束,D2切片index=1的数据
print('4)', b[0,1,::2],'\n') # 切片D0 index=0,D1 index=1,D2中起始到终止的正序步长2的数据
print('5)', b[:,1],'\n') # D0和D2不作约束,切片D1 index=1的数据
print('=5)', b[:,1,:],'\n') # D0和D2不作约束,切片D1 index=1的数据
return 0
if __name__ == '__main__':
sys.exit(main(len(sys.argv), sys.argv, os.environ))
- output:
b:
[[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[13 14 15 16]
[17 18 19 20]
[21 22 23 24]]]
1) [ 1 13]
2) [[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
3) [[ 2 6 10]
[14 18 22]]
4) [5 7]
5) [[ 5 6 7 8]
[17 18 19 20]]
=5) [[ 5 6 7 8]
[17 18 19 20]]
[Finished in 1.4s]