Como comparar duas listas em Python

Python oferece várias maneiras de comparar as duas listas. Comparação é o processo em que os itens de dados são verificados em relação a outro item de dados da lista, sejam eles iguais ou não.

 list1 - [11, 12, 13, 14, 15] list2 - [11, 12, 13, 14, 15] Output - The lists are equal  

Os métodos de comparação de duas listas são fornecidos abaixo.

  • A função cmp()
  • A função set() e o operador ==
  • A função sort() e o operador ==
  • A função coleção.counter()
  • As funções reduzir() e map()

A função cmp()

O Pitão A função cmp() compara os dois objetos Python e retorna os valores inteiros -1, 0, 1 de acordo com a comparação.

Nota - Não é usado na versão Python 3.x.

A função set() e o operador ==

Pitão definir() função manipular a lista no conjunto sem cuidar da ordem dos elementos. Além disso, usamos o operador igual a (==) para comparar os itens de dados da lista. Vamos entender o exemplo a seguir.

Exemplo -

 list1 = [11, 12, 13, 14, 15] list2 = [12, 13, 11, 15, 14] a = set(list1) b = set(list2) if a == b: print('The list1 and list2 are equal') else: print('The list1 and list2 are not equal')  

Saída:

 The list1 and list2 are equal  

Explicação:

No exemplo acima, declaramos as duas listas para serem comparadas entre si. Convertemos essas listas no conjunto e comparamos cada elemento com a ajuda do operador ==. Todos os elementos são iguais em ambas as listas, então se o bloco for executado e impresso o resultado.

O método sort() com operador ==

Pitão organizar() função é usada para classificar as listas. Os elementos da mesma lista têm a mesma posição de índice que isso significa; listas são iguais.

Nota - No método sort(), podemos passar os itens da lista em qualquer ordem porque estamos classificando a lista antes da comparação.

Vamos entender o seguinte exemplo -

Exemplo -

 import collections list1 = [10, 20, 30, 40, 50, 60] list2 = [10, 20, 30, 50, 40, 70] list3 = [50, 10, 30, 20, 60, 40] # Sorting the list list1.sort() list2.sort() list3.sort() if list1 == list2: print('The list1 and list2 are the same') else: print('The list1 and list3 are not the same') if list1 == list3: print('The list1 and list2 are not the same') else: print('The list1 and list2 are not the same')  

Saída:

 The list1 and list3 are not the same The list1 and list2 are not the same  

A função coleção.counter()

O módulo de coleta fornece o contador(), que comparam a lista de forma eficiente. Armazena os dados em formato de dicionário: e conta a frequência dos itens da lista.

Nota – A ordem dos elementos da lista não importa nesta função.

Exemplo -

 import collections list1 = [10, 20, 30, 40, 50, 60] list2 = [10, 20, 30, 50, 40, 70] list3 = [50, 10, 30, 20, 60, 40] if collections.Counter(list1) == collections.Counter(list2): print('The lists l1 and l2 are the same') else: print('The lists l1 and l2 are not the same') if collections.Counter(list1) == collections.Counter(list3): print('The lists l1 and l3 are the same') else: print('The lists l1 and l3 are not the same')  

Saída:

 The lists list1 and list2 are not the same The lists list1 and list3 are the same  

A redução() e o mapa()

O mapa() function aceita uma função e um objeto iterável Python (lista, tupla, string, etc) como argumentos e retorna um objeto de mapa. A função é implementada em cada elemento da lista e retorna um iterador como resultado.

Além da reduzir() O método implementa a função fornecida no objeto iterável recursivamente.

Aqui, usaremos os dois métodos em combinação. O mapa() função implementaria a função (pode ser definida pelo usuário ou função lambda) para cada objeto iterável e o reduzir() função cuidar disso se aplicaria de maneira recursiva.

Nota - Precisamos importar o módulo functool para usar a função reduzir().

Vamos entender o exemplo a seguir.

Exemplo -

 import functools list1 = [10, 20, 30, 40, 50] list2 = [10, 20, 30, 50, 40, 60, 70] list3 = [10, 20, 30, 40, 50] if functools.reduce(lambda x, y: x and y, map(lambda a, b: a == b, list1, list2), True): print('The list1 and list2 are the same') else: print('The list1 and list2 are not the same') if functools.reduce(lambda x, y: x and y, map(lambda a, b: a == b, list1, list3), True): print('The list1 and list3 are the same') else: print('The list1 and list3 are not the same')  

Saída:

 The list1 and list2 are not the same The list1 and list3 are the same  

Nesta seção, cobrimos vários métodos de comparação de duas listas em Python.