Teemu Leivo
Teemu Leivo

Reputation: 341

Find all occurences of an element in a matrix in Python

I have a list of lists and I want to find the cordinates of all occurences. I managed to do it, but I wonder if there is a better way to do it using numpy where for example.

This is what I did:

my_list = [[1,2,3,1, 3], [1,3,2]]

target_value = 3
locations = []
for k in range(len(my_list)):
    indices = [i for i, x in enumerate(my_list[k]) if x == target_value]
    locations.append((k, indices))
locations2 = []
for row in locations:
    for i in row[1]:
        locations2.append((row[0], i))
print locations2 # prints [(0, 2), (0, 4), (1, 1)]

Upvotes: 1

Views: 1076

Answers (1)

DSM
DSM

Reputation: 353019

While you could get this to work in numpy, numpy isn't all that happy with ragged arrays. I think the pure python comprehension version looks okay:

>>> my_list = [[1,2,3,1, 3], [1,3,2]]
>>> [(i,j) for i,x in enumerate(my_list) for j,y in enumerate(x) if y == 3]
[(0, 2), (0, 4), (1, 1)]

Upvotes: 3

Related Questions