首页 > 解决方案 > 如何一个班轮访问列表中的numpy数组?

问题描述

给定列表中的数组

import numpy as np
n_pair = 5
np.random.seed ( 0 )
nsteps = 4
nmethod = 2
nbands = 3
t_band=0
t_method=0
t_step=0
t_sbj=0
t_gtmethod=1
all_sub = [[np.random.rand ( nmethod, nbands, 2 ) for _ in range ( nsteps  )] for _ in range ( 3)]

然后从每个列表中提取数组数据点,如下所示

this_gtmethod=[x[t_step][t_method][t_band][t_gtmethod] for x in all_sub]

但是,我想避免循环,而是想直接访问所有三个元素,如下所示

this_gtmethod=all_sub[:][t_step][t_method][t_band][t_gtmethod]

但是,如上所述索引元素时,它不会返回预期的结果

我可以知道我在哪里做错了吗?

标签: pythonnumpyindexing

解决方案


这种切片和索引最好用 Numpy 数组而不是列表来完成。

如果你做成all_sub一个 Numpy 数组,你可以通过简单的切片来达到你想要的结果。

all_sub = np.array(all_sub)
this_gtmethod = all_sub[:, t_step, t_method, t_band, t_gtmethod]

结果与您的循环示例相同。


推荐阅读