Checking for data inside a list of lists

Asked

Viewed 60 times

-1

I have a list of lists. So:

lista = [['2746', '8512.20.21', '2 - Estrangeira - Adquirida no mercado interno, exceto a indicada no código 7', 'SL-121410', '6949999876781'],['2747', '8512.20.21', '2 - Estrangeira - Adquirida no mercado interno, exceto a indicada no código 7', 'SL-121410CR', '6949999876798'],['2794', '8512.20.21', '2 - Estrangeira - Adquirida no mercado interno, exceto a indicada no código 7', 'SL-121510', '6949999876811']]

And I’d like to check if there’s a string inside that list. I tried to use the in, but I didn’t get the result.

EAN = "6949999876811"
    
if EAN in lista:
        print(f'EAN {EAN} encontrado')

    else:
        print(f'EAN {EAN} não encontrado')

1 answer

3


You have a list of lists (each element of lista is another list):

lista = [
  # primeiro elemento de "lista"
  ['2746', '8512.20.21', '2 - Estrangeira - Adquirida no mercado interno, exceto a indicada no código 7', 'SL-121410', '6949999876781'],
  # segundo elemento de "lista"
  ['2747', '8512.20.21', '2 - Estrangeira - Adquirida no mercado interno, exceto a indicada no código 7', 'SL-121410CR', '6949999876798'],
  # terceiro elemento de "lista"
  ['2794', '8512.20.21', '2 - Estrangeira - Adquirida no mercado interno, exceto a indicada no código 7', 'SL-121510', '6949999876811']
]

When you do EAN in lista, the value of EAN is compared with these sublists, and not with the values within them).

Therefore, you should go through these sublists and check if the value is within them:

EAN = "6949999876811"

for sublista in lista: # para cada sublista
    if EAN in sublista: # verifica se está na sublista
        print(f'EAN {EAN} encontrado')
        break # encontrei, pode interromper o for
else: # não encontrou nenhum
    print(f'EAN {EAN} não encontrado')

If EAN is found, I use break to interrupt the for, 'cause if I have, I understand you don’t have to keep looking.

If you don’t find any (i.e., if the break not called), he falls into the else (note that this else is from for and not of if - in Python this is perfectly normal) and prints the respective message.


If you want, you can also treat all sublists as a single eternal, so it is possible to verify the existence of EAN right. For this, just use the module itertools:

from itertools import chain

if EAN in chain.from_iterable(lista):
    print(f'EAN {EAN} encontrado')
else:
    print(f'EAN {EAN} não encontrado')

chain.from_iterable makes all sublists of lista are treated as a single iterable, so you can check whether EAN exists directly in it.


To another answer (which has been deleted) also works, but the detail is that the comprehensilist on used there ([item for sublista in lista for item in sublista]) ends up creating another list containing all elements. Of course, for a few elements - as is the case - it doesn’t make that much difference, but I wouldn’t create another list just to look for an element, and it is possible to do so without creating any other additional structure (in the case of chain.from_iterable, it creates an iterable, which iterates through the elements and then discards them, so there is no creation of another list).

This can be corrected by changing the brackets into parentheses (as it becomes one Generator Expression, which also computes the elements one at a time, instead of creating another list). But there you can use together with any, to check if there is any element that satisfies the condition:

# se tem algum elemento que é igual a EAN
if any(item for item in sublista for sublista in lista if EAN == item):
    print(f'EAN {EAN} encontrado')
else:
    print(f'EAN {EAN} não encontrado')
  • 1

    True! Good! Hug!

Browser other questions tagged

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