如果我分别沿一个维度定义了两个切片对象,是否可以将它们组合起来以获得可用于对 numpy 数组进行切片的多维切片对象?
mat = np.zeros((10,10), dtype=np.uint8)
s1 = slice(0,5)
s2 = slice(0,5)
mat[s1,s2] # I want to achieve this effect with one slice object
slice2d = slice(s1, s2) # does not throw an error
mat[slice2d] # but this does not work
正如@unutbu所指出的,多维切片实际上是slice
对象的tuple
或list
,然后:
slice2d = (s1, s2)
mat[slice2d]
会工作。同样,您可以将其扩展到 3-D、...、N-D 数组:
slice3d = (s1, s2, s3)
...
sliceNd = (s1, s3, s3, ..., sN)