因为numpy.array可以创建任意维度的数组,因此可以通过下标访问数组元素。
import numpy as np
#构建一个size为(3,3,3)的数组
Y = np.array([[[1, 1, 1],
[2, 0, 0],
[3, 0, 0]],
[[4, 4, 4],
[5, 0, 0],
[6, 0, 0]],
[[7, 7, 7],
[8, 0, 0],
[9, 0, 0]]])
print("shape of Y is ",Y.shape,", type of Y is ",type(Y))
print(Y)
print("#"*50)
new = Y[1:3,1:2] #索引均从0开始;1:3相当于左闭右开,从1到3但不包括3;1:2同理
print("shape of new is :",new.shape)
print(new)
##################################################################################################################################################################################
output:
shape of Y is (3, 3, 3) , type of Y is <class 'numpy.ndarray'>
[[[1 1 1]
[2 0 0]
[3 0 0]]
[[4 4 4]
[5 0 0]
[6 0 0]]
[[7 7 7]
[8 0 0]
[9 0 0]]]
##################################################
shape of new is : (2, 1, 3)
[[[5 0 0]]
[[8 0 0]]]
Process finished with exit code 0
注意下标访问数组元素的规则。
import numpy as np
#构建一个size为(3,3,3)的数组
Y = np.array([[[1, 1, 1],
[2, 0, 0],
[3, 0, 0]],
[[4, 4, 4],
[5, 0, 0],
[6, 0, 0]],
[[7, 7, 7],
[8, 0, 0],
[9, 0, 0]]])
print("shape of Y is ",Y.shape,", type of Y is ",type(Y))
print(Y)
print("#"*50)
print(Y[0:3,1])
print("#"*30)
print(Y[0:3][1]) #Y[0:3]相当于Y本身
##################################################################################################################################################################################
output:
shape of Y is (3, 3, 3) , type of Y is <class 'numpy.ndarray'>
[[[1 1 1]
[2 0 0]
[3 0 0]]
[[4 4 4]
[5 0 0]
[6 0 0]]
[[7 7 7]
[8 0 0]
[9 0 0]]]
##################################################
[[2 0 0]
[5 0 0]
[8 0 0]]
##############################
[[4 4 4]
[5 0 0]
[6 0 0]]
Process finished with exit code 0
注意shape[1:]与shape[1]的区别:
(1) shape[1:]的类型是tuple,而shape[1]的类型是int;
(2) [1:]的作用为获取从索引1到最后一个位置的索引值(默认首位索引为0),可用于字符串
、列表
和元组。
详见python 中[1:]、[:-1]和[::-1]详解_淮水竹亭-CSDN博客_python[1,-1]和【Python 小知识】[:-1] 和 [::-1]_VirusScanLog的博客-CSDN博客。
import numpy as np
import scipy.io as sio
org = sio.loadmat('I.mat')['I'] #org.shape为(4, 5, 3) 格式H,W,C
new = np.zeros((4, 5, 3)) #new.shape为(4, 5, 3)
print("shape of org is ",org.shape)
print("shape of new is ",new.shape)
new = org[:,:,1]
print("shape of new is ",new.shape)
newnew = org.shape[1:]
print("[1:]: newnew is ",newnew,", and type of newnew is ",type(newnew))
newnew = org.shape[1]
print("[1]: newnew is ",newnew,", and type of newnew is ",type(newnew))
##################################################################################################################################################################################
output:
shape of org is (4, 5, 3)
shape of new is (4, 5, 3)
shape of new is (4, 5)
[1:]: newnew is (5, 3) , and type of newnew is <class 'tuple'>
[1]: newnew is 5 , and type of newnew is <class 'int'>
Process finished with exit code 0
参考文献:
python 中[1:]、[:-1]和[::-1]详解_淮水竹亭-CSDN博客_python[1,-1]
【Python 小知识】[:-1] 和 [::-1]_VirusScanLog的博客-CSDN博客