Python 提供了多種方法來比較這兩個列表。比較是將的數據項與列表中的另一個數據項進行檢查的過程,無論它們是否相同。
list1 - [11, 12, 13, 14, 15]
list2 - [11, 12, 13, 14, 15]
Output - The lists are equal
下面給出了比較兩個列表的方法。
cmp()函數
set()函數和==運算符
sort()函數和==運算符
collection.counter()函數
reduce()和 map()函數
cmp()函數
Python cmp()函數比較兩個 Python 對象,根據比較結果返回整數值-1,0,1。
注意——它在 Python 3.x 版本中不使用。
set()函數和==運算符
Python set() 函數操縱列表進入集合而不考慮元素的順序。此外,我們使用等于運算符(==)來比較列表的數據項。讓我們理解下面的例子。
示例-
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")
輸出:
The list1 and list2 are equal
解釋:
在上面的例子中,我們已經聲明了要相互比較的兩個列表。我們將這些列表轉換成集合,并在==運算符的幫助下比較每個元素。兩個列表中的所有元素都是相等的,那么如果執行了 block 并打印了結果。
帶有==運算符的 sort()方法
Python sort() 函數用于排序列表。同一個列表的元素是指同一個索引位置;列表是平等的。
注意——在 sort()方法中,我們可以以任何順序傳遞列表項,因為我們是在比較之前排序列表。
讓我們理解下面的例子-
示例-
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")
輸出:
The list1 and list3 are not the same
The list1 and list2 are not the same
collection.counter()函數
collections
模塊提供計數器(),,有效比較列表。它以字典格式<值> : <頻率>存儲數據,并計算列表項目的頻率。
注意——列表元素的順序在這個函數中并不重要。
示例-
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")
輸出:
The lists list1 and list2 are not the same
The lists list1 and list3 are the same
reduce()和 map()
map() 函數接受一個函數和 Python 可迭代對象(列表、元組、字符串等)作為參數,并返回一個 map 對象。該函數對列表的每個元素實現,并返回一個迭代器作為結果。
此外, reduce() 方法對可迭代對象遞歸實現給定的函數。
這里,我們將結合使用這兩種方法。 map() 函數將函數(可以是用戶定義的函數或 lambda 函數)實現到每個可迭代對象,而 reduce() 函數負責以遞歸方式應用。
注意-我們需要導入 functool 模塊來使用 reduce()函數。
讓我們理解下面的例子。
示例-
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")
輸出:
The list1 and list2 are not the same
The list1 and list3 are the same
在本節中,我們已經介紹了在 Python 中比較兩個列表的各種方法。