Comparison List of lists and list python

2

I am looking to make a comparison of a list with a list of lists. With this code I can do it between 2 lists but the problem happens when it is a list with a list of lists.

I am looking to edit my code to be corrected.

lista1=["paco","pepe","luis"]
lista2=["diego","mari","luis"]
comparacion = []

for item in lista1:
  if item in lista2:
    comparacion.append(item)

Code to correct:

lista1=["paco","pepe","luis"]
lista2=[["artur","2"],["paco","5"],["pepe","2"],["luis","2"],["beto","2"]]
comparacion = []

for item in lista1:
  if item in lista2:
    comparacion.append(item)

print comparacion
#Busco algo asi como respuesta:
>>>comparacion=[["paco","5"],["pepe","2"],["luis","2"]]
    
asked by Martin Bouhier 11.12.2017 в 21:29
source

2 answers

1

If we want something simple, this is what I would do:

lista1=["paco","pepe","luis"]
lista2=[["artur","2"],["paco","5"],["pepe","2"],["luis","2"],["beto","2"]]
comparacion = []

for item in lista1:
  comparacion.extend([e for e in lista2 if item == e[0]])

print comparacion
  • [e for e in lista2 if item == e[0]] returns a list of at least one element where the name of lista1 is found in the first element of the sublists of Lista2
  • With extend we are simply adding the previous list to comparacion
answered by 11.12.2017 / 22:39
source
1

Assuming that the item to be searched is always the first item in nested lists, it simply iterates and indexes this item. It is recommended that list1 be a set or that you convert it to one since the search is considerably faster with a hash table in between:

lista1=["paco","pepe","luis"]
lista2=[["artur","2"],["paco","5"],["pepe","2"],["luis","2"],["beto","2"]]
aux = set(lista1)
comparacion = [item for item in lista2 if item[0] in aux]

If you want to perform the search in the whole sublist and not only in one position (for example, that both ["luis", "5"] and ["5", "luis"] are validated) you must also iterate over the sublist or use the intersection of sets:

comparacion = [item for item in lista2 if set(item) & aux]

If you work with significant amounts of data use whenever you can list compression, append is quite slow in comparison.

    
answered by 11.12.2017 в 22:41