用列表索引多维numpy数组

Kai*_*oto 2 python arrays indexing numpy multidimensional-array

我在使用python 2.7访问多维numpy数组中的数据时遇到问题。目标是读取位置存储在列表中的多个值。

import numpy as np
matrix=np.ones((10,30,5))

positions=[]
positions.append([1,2,3])
positions.append([4,5,6])

for i in positions:
    print matrix[i]
Run Code Online (Sandbox Code Playgroud)

我想要的是:

print matrix[1,2,3]
Run Code Online (Sandbox Code Playgroud)

但是我得到:

print [matrix[1], matrix[2], matrix[3]]
Run Code Online (Sandbox Code Playgroud)

您能给我提示正确的索引编制吗?谢谢!

Ash*_*ary 5

索引文档

在Python中,x[(exp1, exp2, ..., expN)]等效于x[exp1, exp2,..., expN];后者只是前者的语法糖。

因此,将元组传递给,而不是将其传递给列表matrix

for i in positions:
    print matrix[tuple(i)]
Run Code Online (Sandbox Code Playgroud)

列表用于在特定索引处选择项目,即索引数组

>>> arr = np.random.rand(10)
>>> arr
array([ 0.56854322,  0.21189256,  0.72516831,  0.85751778,  0.29589961,
        0.90989207,  0.26840669,  0.02999548,  0.65572606,  0.49436744])
>>> arr[[0, 0, 5, 1, 5]]
array([ 0.56854322,  0.56854322,  0.90989207,  0.21189256,  0.90989207])
Run Code Online (Sandbox Code Playgroud)