假设我创建了一个任意维度 (n) 的数组。
#assign the dimension
>>> n=22
#create the numpy array
>>> TheArray=zeros([2]*n)
>>> shape(TheArray)
(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
使用一些代码(在此示例中跳过)来填充数组的值。
现在,尝试访问数组的一些值
>>> TheArray[0:2,0:2,0:2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
array([[[ 0., 0.],
[ 0., 0.]],
[[ 0., 0.],
[ 0., 0.]]])
如何制作 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
泛化到 n 的部分语法?
最佳答案
一种方法是使用 numpy.s_ :
In [55]: m = arange(2**6).reshape([2]*6)
In [56]: m.shape
Out[56]: (2, 2, 2, 2, 2, 2)
In [57]: m[:2,:2,:2,0,0,0]
Out[57]:
array([[[ 0, 8],
[16, 24]],
[[32, 40],
[48, 56]]])
In [58]: m[s_[:2, :2, :2] + (0,)*(n-3)]
Out[58]:
array([[[ 0, 8],
[16, 24]],
[[32, 40],
[48, 56]]])
我猜你可以去掉硬编码的 -3..
In [69]: m[(s_[:2, :2, :2] + (0,)*m.ndim)[:m.ndim]]
Out[69]:
array([[[ 0, 8],
[16, 24]],
[[32, 40],
[48, 56]]])
但老实说,如果需要的话,我可能会把它包装在一个函数中。
关于python - 任意维度的numpy数组切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12903367/