Python 给定索引列表的一维数组的任意维切片数

Python 给定索引列表的一维数组的任意维切片数,python,numpy,slice,numpy-ndarray,numpy-slicing,Python,Numpy,Slice,Numpy Ndarray,Numpy Slicing,我有一个numpy ndarrayarr和index,一个指定特定条目的索引列表。对于具体性,我们采取以下措施: arr = np.arange(2*3*4).reshape((2,3,4)) indices= [1,0,3] 我有代码通过arr进行1d切片,观察除一个索引之外的所有索引n: arr[:, indices[1], indices[2]] # n = 0 arr[indices[0], :, indices[2]] # n = 1 arr[indices[0], indice

我有一个numpy ndarray
arr
index
,一个指定特定条目的索引列表。对于具体性,我们采取以下措施:

arr = np.arange(2*3*4).reshape((2,3,4))
indices= [1,0,3]
我有代码通过
arr
进行1d切片,观察除一个索引之外的所有索引
n

arr[:, indices[1], indices[2]]  # n = 0
arr[indices[0], :, indices[2]]  # n = 1
arr[indices[0], indices[1], :]  # n = 2
我想将我的代码更改为循环
n
,并支持任意维度的
arr

我查看了文档中的条目,找到了有关
slice()
np.s(
)的信息。我能够拼凑出我想要的东西:

def make_custom_slice(n, indices):
    s = list()
    for i, idx in enumerate(indices):
        if i == n:
            s.append(slice(None))
        else:
            s.append(slice(idx, idx+1))
    return tuple(s)


for n in range(arr.ndim):
    np.squeeze(arr[make_custom_slice(n, indices)])
其中,
np.挤压
用于移除长度为1的轴。如果没有此项,则生成的数组具有shape
(arr.shape[n],1,1,…)
,而不是
(arr.shape[n],)


是否有更惯用的方法来完成此任务?

对上述解决方案进行了一些改进(可能仍然有一个单行程序或更高性能的解决方案):

整数值
idx
可用于替换切片对象
slice(idx,idx+1)
。因为大多数索引都是直接复制的,所以从索引的副本开始,而不是从头开始构建列表


以这种方式构建时,
arr[make_custom_slice(n,index)
的结果具有预期的维度,
np.squence
是不必要的。

是否有更惯用的方法来完成此任务使用Numpy完成任务的惯用方法通常包括不编写循环。我同意这一点。我在下面发布的改进删除了构建切片对象的函数中的循环。我不确定该函数是否可以在n中矢量化以删除调用它的循环。
def make_custom_slice(n, indices):
    s = indices.copy()
    s[n] = slice(None)
    return tuple(s)


for n in range(arr.ndim):
    print(arr[make_custom_slice(n, indices)])