簡體   English   中英

如何在Python中的二維數組中找到值的索引?

[英]How to find the index of a value in 2d array in Python?

我需要弄清楚如何在 2d numpy 數組中找到一個值的所有索引。

例如,我有以下二維數組:

([[1 1 0 0],
  [0 0 1 1],
  [0 0 0 0]])

我需要找到所有 1 和 0 的索引。

1: [(0, 0), (0, 1), (1, 2), (1, 3)]
0: [(0, 2), (0, 3), (1, 0), (1, 1), (the entire all row)]

我試過這個,但它沒有給我所有的索引:

t = [(index, row.index(1)) for index, row in enumerate(x) if 1 in row]

基本上,它只給我每行[(0, 0), (1, 2)]一個索引。

您可以使用np.where返回 x 和 y 索引數組的元組,其中給定條件在數組中成立。

如果a是數組的名稱:

>>> np.where(a == 1)
(array([0, 0, 1, 1]), array([0, 1, 2, 3]))

如果你想要一個 (x, y) 對的列表,你可以zip這兩個數組:

>>> zip(*np.where(a == 1))
[(0, 0), (0, 1), (1, 2), (1, 3)]

或者,更好的是,@jme 指出np.asarray(x).T可以是一種更有效的生成對的方法。

您提供的列表理解的問題在於它只深入一層,您需要一個嵌套的列表理解:

a = [[1,0,1],[0,0,1], [1,1,0]]

>>> [(ix,iy) for ix, row in enumerate(a) for iy, i in enumerate(row) if i == 0]
[(0, 1), (1, 0), (1, 1), (2, 2)]

話雖如此,如果您使用的是 numpy 數組,最好使用 ajcr 建議的內置函數。

使用 numpy, argwhere可能是最好的解決方案:

import numpy as np

array = np.array([[1, 1, 0, 0],
                  [0, 0, 1, 1],
                  [0, 0, 0, 0]])

solutions = np.argwhere(array == 1)
print(solutions)

>>>
[[0 0]
 [0 1]
 [1 2]
 [1 3]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM