[英]Python: How to get values of a multi-dimensional array at certain indexed positions?
如果我有一個多維 numpy 數組,例如:
a = [[0 1 2]
[3 4 5]
[6 7 8]]
如何一步獲取特定索引位置的值? 例如,如果要定義成對的索引,例如:
indices = [[0,0], [1,1], [2,2]]
我想:
a[indices] = [0, 4, 8]
請注意,這確實適用於一維數組( Python:如何在某些索引位置獲取數組的值? ),但我看不出如何使其在一維以上工作。 我正在使用 Python 3.7。
改編自 Prasanna 的評論
a = [[0 1 2]
[3 4 5]
[6 7 8]]
indices = [[0,0], [1,1], [2,2]]
a[indices] = [a[pair[0]][pair[1]] for pair in indices]
這是通過使用 for each 循環,遍歷索引數組中的每一對,然后將每個給定索引處的值添加到最終結果中來實現的。
pair
每對被索引陣列中,並且表示在每個索引對indices
。 在您的示例中,第一次迭代中為[0,0]
,第二次為[1,1]
,第三次為[2,2]
。
正如在您鏈接的一維答案中一樣,您可以使用numpy
在二維中優雅地完成此操作:
a = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
rows, columns = zip([0, 0], [1, 1], [2, 2])
print(a[rows, columns])
print
的輸出將是:
array([0, 4, 8])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.