【问题标题】:Python np.arrays accessing indices with variablePython np.arrays 使用变量访问索引
【发布时间】:2021-12-31 14:03:17
【问题描述】:

我有一个 n 维 numpy 数组 A,我有一个索引变量 i=[x,y,z]。

通常,如果我想在这个索引处获取 A 的元素,我可以做 A[x,y,z]。如果我只想使用 A 和 i,我该怎么做。

之所以必须这样做是因为我不知道A的维度。

【问题讨论】:

  • A[tuple(i))] 应用列表
  • A[x,y,z] 等价于A[(x,y,z)]

标签: arrays numpy


【解决方案1】:

您可以尝试遍历数组idx 中的每个元素,以访问给定数组arr 中的某个位置。

import numpy as np
d3 = np.zeros((4,4,4))
d3[3,1,2] = 12
d4 = np.zeros((4,4,4,4))
d4[2,1,2,1] = 24
d5 = np.zeros((4,4,4,4,4))
d5[2,3,1,0,1] = 36

def nDimensionalIndex(arr,idx):
    temp = arr
    for key in idx:
        temp = temp[key]
    return temp

print(nDimensionalIndex(d3,[3,1,2]))     # returns 12.0
print(nDimensionalIndex(d4,[2,1,2,1]))   # returns 24.0
print(nDimensionalIndex(d5,[2,3,1,0,1])) # returns 36.0

通过使用传递数组的临时副本,您可以缩小temp 的维度以找到idx 的值。这允许您在 n 维数组中获取值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    • 2015-05-09
    相关资源
    最近更新 更多