gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:33:40 24 4
gpt4 key购买 nike

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

关于python - 如何在 python 中访问具有索引数组的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48461042/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com