I didn’t go through the other answers in depth, but I was a little surprised by the amount of code for a simple task. So I propose here 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 a little code:
x in lista if valor in x
will search which is the sub-list which is the desired value, storing this sub-list in x
. The value returned will be (lista.index(x), x.index(valor))
, where the first will be the sub-list index in the list and the second value the index of the desired value within the sub-list. Note that the value returned will be a list of all occurrences of the value. For example, the value "4" is present twice in the list and therefore has two returned values.
See working on Ideone | Repl.it
The above solution fails when a sub-list has the same value several times. For example, in the input:
lista = [['julian', '0', '4', '4'], ['ana', '10', '4']]
It would be expected that the exit to search(lista, '4')
were the pairs (0, 2)
, (0, 3)
and (1, 2)
. because the first sub-list has twice the value '4'
, but it is, in fact, just (0, 2)
and (1, 2)
, because it stops searching when it finds the first element. To get around this, I adapted the solution to search for all 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 on Ideone | Repl.it
Thus, the exit of search(lista, '4')
will be:
[[(0, 2), (0, 3)], [(1, 2)]]
Just 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 on Ideone | Repl.it
In case the same element exists multiple times, I believe that a
yield
should solve– Jefferson Quesado
I think I understood, so if there were more than two lists as in the example I would have to increase the loops?
– Julian Vitor
@Julianvitor Editei to search for more than one word occurrence. We just need to remove the
breaks
, because the program didn’t search the entire list - in addition, we need to save more than one result, so I added a new list - have a look.– Daniel