我知道如何通过索引访问向量中的元素:
test = numpy.array([1,2,3,4,5,6])
indices = list([1,3,5])
print(test[indices])
Run Code Online (Sandbox Code Playgroud)
给出正确答案:[2 4 6]
但我正在尝试使用 2D 矩阵做同样的事情,例如:
currentGrid = numpy.array( [[0, 0.1],
[0.9, 0.9],
[0.1, 0.1]])
indices = list([(0,0),(1,1)])
print(currentGrid[indices])
Run Code Online (Sandbox Code Playgroud)
这应该为我显示“[0.0 0.9]”,表示矩阵中 (0,0) 处的值和 (1,1) 处的值。而是显示“[ 0.1 0.1]”。此外,如果我尝试使用 3 个索引:
indices = list([(0,0),(1,1),(0,2)])
Run Code Online (Sandbox Code Playgroud)
我现在收到以下错误:
Traceback (most recent call last):
File "main.py", line 43, in <module>
print(currentGrid[indices])
IndexError: too many indices for array
Run Code Online (Sandbox Code Playgroud)
我最终需要对这些索引处的所有元素应用一个简单的 max() 操作,并且需要以最快的方式来实现优化。
我究竟做错了什么 ?如何访问矩阵中的特定元素以非常有效的方式(不使用列表理解或循环)对它们进行一些操作。