如何根据参数创建一个切片数组的函数

Gla*_*wed 3 python numpy

所以,假设我有一个2x2x2x2x2numpy数组G.我想创建一个根据参数ab(在哪里ab是索引)切片的函数.

例如,我希望函数返回G[0,:,0,:,:]if a=0b=2.这可能吗?

unu*_*tbu 5

您可以创建切片列表:

idx = [0 if i in axes else slice(None) for i in range(G.ndim)]
Run Code Online (Sandbox Code Playgroud)

然后回来 G[idx]:

import numpy as np
np.random.seed(2015)

def getslice(G, axes):
    idx = [0 if i in axes else slice(None) for i in range(G.ndim)]
    return G[idx]

G = np.random.randint(10, size=(2,2,2,2,2,))
assert np.allclose(getslice(G, [0,2]), G[0,:,0,:,:])
Run Code Online (Sandbox Code Playgroud)