简体   繁体   English

使用元组索引 Numpy 数组维度

[英]Index Numpy array dimensions with tuple

I have a numpy array such as arr = np.arange(16).reshape(2,2,2,2)我有一个 numpy 数组,例如arr = np.arange(16).reshape(2,2,2,2)

I want to dynamically access arr[:, dim2, dim3] , when I have (dim2, dim3) as a tuple.当我将(dim2, dim3)作为元组时arr[:, dim2, dim3]我想动态访问arr[:, dim2, dim3] What is the best way to do this?做这个的最好方式是什么?

Try something like this if the number of dimensions might not be the same for your array:如果您的数组的维数可能不同,请尝试以下操作:

some_tuple = (dim2, dim3) # Could be (dim2, dim3, ..., dimN)

arr[(slice(None),) + some_tuple]

In this particular case, (slice(None),) + some_tuple is the same as (slice(None), dim2, dim3) .在这种特殊情况下, (slice(None),) + some_tuple(slice(None), dim2, dim3) slice(None) is more or less equivalent to " : ", but it can be used in more places than " : ". slice(None)或多或少等同于“ : ”,但它可以用在比“ : ”更多的地方。 Notice that I put slice(None) in a single-element tuple (ie (slice(None),) ) so that I can add it to some_tuple .请注意,我将slice(None)放在单元素元组中(即(slice(None),) ),以便我可以将其添加到some_tuple Notice as well that there's a comma after slice(None) , ie, I don't just write (slice(None)) without a comma.还要注意slice(None)之后有一个逗号,即,我只是写(slice(None))没有逗号。 It won't work without the extra comma.如果没有额外的逗号,它将无法工作。

some_tuple = (dim2, dim3) arr[:, some_tuple[0], some_tuple[1]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM