【问题标题】:How can I access an array with an array of indexes in python?如何在 python 中访问具有索引数组的数组?
【发布时间】:2018-07-05 18:35:22
【问题描述】:

我想访问一个带有索引数组的多维 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]])

结果是构建一个新数组,其中索引数组的每个值从被索引的数组中选择一行,结果数组具有结果形状(索引元素的数量,行的大小)。

谢谢。

【问题讨论】:

标签: python arrays numpy indexoutofboundsexception


【解决方案1】:

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

A[tuple(a)]
3

【讨论】:

    猜你喜欢
    • 2021-08-19
    • 2022-12-12
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2014-07-25
    相关资源
    最近更新 更多