通过使用元组列表作为 python 中的索引获取 numpy 数组中的元素

Getting elements within a numpy array by using a list of tuples as indices in python

我有一个(整数的)元组列表,循环起来很长。我还有一个 numpy 数组。我想获取列表中每个元组给出的元素,而不必遍历列表。像这样:

mySum = np.sum(myArray(myList))

这当然行不通。我有办法做到这一点吗? 该列表看起来像这样:myList = [(1,2,2),(0,0,2),...,(100,122,200)].

myArray 是一个 3d numpy 数组。

您可以提取每个维度的索引,然后对 numpy 数组进行切片(假设 myArray 是一个具有三个维度的数组):

# Define the indices
myList = [(1,2,2), (0,0,2), (100,122,200), (3, 4, 5)]
# Define the array (just random numbers)
myArray = np.random.uniform(size=(101, 201, 201))
# Extract the indices
a, b, c = np.transpose(myList)
# Slice the numpy array and sum
mySum = np.sum(myArray[a, b, c])