Ujjal Shaha
Ujjal Shaha

Reputation: 13

How to find all the indices of all the elements in a 2d matrix using Python?

I have a multidimensional matrix where I want to find the indices of all the elements in the matrix in the form (i,j). Oh and unfortunately i cannot use the numpy module. So, codes without 'numpy' would be much appreciated guys.

The matrix is:

[[0, 1.0, 1.0, 1.0, 5.0, 4.0], 
 [1.0, 0, 1.0, 1.0, 5.0, 4.0], 
 [1.0, 1.0, 0, 1.0, 1.0, 1.0], 
 [1.0, 1.0, 1.0, 0, 1.0, 1.0], 
 [5.0, 5.0, 1.0, 1.0, 0, 0], 
 [4.0, 4.0, 1.0, 1.0, 0, 0]]

Upvotes: 0

Views: 967

Answers (1)

xnx
xnx

Reputation: 25478

EDIT: if you mean a list of all index pairs (for any element) you can do:

[(i,j) for i in range(len(m)) for j in range(len(m[i]))]

[(0, 0),
 (0, 1),
 (0, 2),
 (0, 3),
...
 (5, 4),
 (5, 5)]

For the indexes of nonzero elements, add a conditional:

[(i,j) for i in range(len(m)) for j in range(len(m[i])) if m[i][j] != 0]

[(0, 0),
 (0, 1),
 (0, 2),
 (0, 3),
...
 (5, 2),
 (5, 3)]

You can find the indices of each element with a particular value, val with a double list comprehension:

m = [[0, 1.0, 1.0, 1.0, 5.0, 4.0], 
     [1.0, 0, 1.0, 1.0, 5.0, 4.0], 
     [1.0, 1.0, 0, 1.0, 1.0, 1.0], 
     [1.0, 1.0, 1.0, 0, 1.0, 1.0], 
     [5.0, 5.0, 1.0, 1.0, 0, 0], 
     [4.0, 4.0, 1.0, 1.0, 0, 0]]

val = 1.0
[(i, j) for i, row in enumerate(m) for j, v in enumerate(row) if val==v]

[(0, 1),
 (0, 2),
 (0, 3),
 (1, 0),
 (1, 2),
 (1, 3),
 (2, 0),
 (2, 1),
 (2, 3),
 (2, 4),
 (2, 5),
 (3, 0),
 (3, 1),
 (3, 2),
 (3, 4),
 (3, 5),
 (4, 2),
 (4, 3),
 (5, 2),
 (5, 3)]

If you're using NumPy (which is good at this sort of thing), you can use np.where, which returns a tuple of row and column coordinates that you can (un)zip:

list(zip(*np.where(a==1.0)))

[(0, 1),
 (0, 2),
 (0, 3),
 (1, 0),
 (1, 2),
 (1, 3),
 (2, 0),
 (2, 1),
 (2, 3),
 (2, 4),
 (2, 5),
 (3, 0),
 (3, 1),
 (3, 2),
 (3, 4),
 (3, 5),
 (4, 2),
 (4, 3),
 (5, 2),
 (5, 3)]

Upvotes: 2

Related Questions