Search for nested list elements

Asked

Viewed 1,176 times

3

I’m having a problem with a code. I have to find a specific element (I know what element it is, but I don’t know its position, because it is random). Under normal conditions, I would use a index and could easily get the position. The problem is that it is a matrix where each row is a nested list, and the method index does not search within lines. What I can do to get the position of the element I want, in this case?

1 answer

4


If you have a fixed number of nests (e.g., lists of lists of elements) - not arbitrary (lists of lists of lists of lists of lists of lists...) - you can use a list comprehension to "flatten it" (Flatten), and then do this search on the resulting list:

>>> x = [[1,2,3],[4,5,6],[7,8,9]]
>>> [e for l in x for e in l].index(5)
4
>>> (4//3, 4%3)
(1, 1)

However, index information is only useful if the lists are the same size... Otherwise (and given the annoying Python mania of using exceptions as control flow) it is best to do a function even:

>>> def indice(elemento, lista):
...     for i,l in enumerate(lista):
...         try:
...             return (i, l.index(elemento))
...         except:
...             pass
...     raise ValueError('O elemento nao esta na lista')
...
>>> indice(5, x)
(1, 1)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.