Skip to main content
 首页 » 编程设计

python之如何在 python 中访问具有索引数组的数组

2024年09月07日7soundcode

我想访问一个带有索引数组的多维 python 数组,使用整个数组来索引目标元素。 让我更好地解释一下:

A = np.arange(4).reshape(2,2) 
a = [1,1] 
>>> A[a[0],a[1]] 
3 

我的意图是在不对索引值进行硬编码的情况下传递数组并获得相同的结果,即值 A[1,1]。我试过了,但我发现的唯一方法是工作方式不同:

>>> A[a] 
array([[2, 3], 
   [2, 3]]) 

What results is the construction of a new array where each value of the index array selects one row from the array being indexed and the resultant array has the resulting shape (number of index elements, size of row).

谢谢。

请您参考如下方法:

将 tuple(不是 list)传递给 __getitem__([..] 索引器)。

A[tuple(a)] 
3