I did not analyze the other answers in depth, but I was a bit surprised at the amount of code for a simple task. So here's another solution:
def search (lista, valor):
return [(lista.index(x), x.index(valor)) for x in lista if valor in x]
The use of this function, in this case, is:
lista = [['julian', '0', '4'], ['ana', '10', '4']]
def search (lista, valor):
return [(lista.index(x), x.index(valor)) for x in lista if valor in x]
print(search(lista, "julian")) # [(0, 0)]
print(search(lista, "ana")) # [(1, 0)]
print(search(lista, "0")) # [(0, 1)]
print(search(lista, "4")) # [(0, 2), (1, 2)]
print(search(lista, "foo")) # []
Explaining the code a little:
x in lista if valor in x
will find the sub-list that is the desired value, storing this sub-list in x
. The returned value will be (lista.index(x), x.index(valor))
, where the first will be the index of the sub-list in the list and the second value the index of the desired value within the sub-list. Note that the returned value will be a list with all occurrences of the value. For example, the value "4" is present twice in the list and therefore has two values returned.
See working at Ideone | Repl.it
The above solution fails when a sublist has the same value multiple times. For example, in the entry:
lista = [['julian', '0', '4', '4'], ['ana', '10', '4']]
The output for search(lista, '4')
would be expected to be the (0, 2)
, (0, 3)
and (1, 2)
pairs. because the first sub-list has twice the value '4'
, but is, in fact, only (0, 2)
and (1, 2)
, because it stops searching when it finds the first element. To get around this, I've adapted the solution to fetch all the elements:
def get_all_indexes(lista, valor):
return (i for i, v in enumerate(lista) if v == valor)
def search(lista, valor):
return (list(product([indice], get_all_indexes(sublista, valor)))
for indice, sublista in enumerate(lista) if valor in sublista)
See working at Ideone | Repl.it
So the output of search(lista, '4')
will be:
[[(0, 2), (0, 3)], [(1, 2)]]
As expected.
Or even easier than that, a simple way:
lista = [['julian', '0', '4', '4'], ['ana', '10', '4']]
def search(lista, valor):
for i, sublista in enumerate(lista):
yield from ((i, j) for j, item in enumerate(sublista) if item == valor)
print( list(search(lista, '4')) ) # [(0, 2), (0, 3), (1, 2)]
See working at Ideone | Repl.it