Numpy根据两个数组给出的不同起始索引在两个轴上切片固定长度

Numpy slicing a fixed length on two axis based on different starting index given by two arrays

比如我有nparray:

a = np.arange(48).reshape((3,4,4))
'''
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]
  [12 13 14 15]]
 [[16 17 18 19]
  [20 21 22 23]
  [24 25 26 27]
  [28 29 30 31]]
 [[32 33 34 35]
  [36 37 38 39]
  [40 41 42 43]
  [44 45 46 47]]]
'''

我有两个数组分别作为axis=1,axis=2切片的起点:

b1 = [0,1,2]
b2 = [1,0,0]

我想实现,像这样的切片:

a[:,b1:b1+2, b2:b2+2] # but this syntax is wrong

获得

[
[
[1,2]
[5,6]
]

[
[20 21]
[24 25]
]

[
[40 41]
[44 45]
]
]

如果您知道执行此操作的正确语法,请告诉我?

您可以使用内置函数 enumeratezip:

list(a[i][f:f+2, s:s+2].tolist() for i, (f, s) in enumerate(zip(b1, b2)))

输出:

[[[1, 2], [5, 6]], [[20, 21], [24, 25]], [[40, 41], [44, 45]]]