如何在 Python 中比较两个列表

17 Mar 2025 | 4 分钟阅读

Python 提供了多种比较两个列表的方法。比较是指检查列表中的数据项是否与另一个列表中的数据项相同或不相同的过程。

比较两个列表的方法如下。

  • cmp() 函数
  • set() 函数和 == 运算符
  • sort() 函数和 == 运算符
  • collection.counter() 函数
  • reduce() 和 map() 函数

cmp() 函数

Python 的 Python cmp() 函数比较两个 Python 对象,并根据比较结果返回整数值 -1、0 或 1。

注意 - Python 3.x 版本中不再使用此功能。

set() 函数和 == 运算符

Python set() 函数 可以操作列表并将其转换为集合,而不考虑元素的顺序。此外,我们使用等于运算符 (==) 来比较列表的数据项。让我们通过下面的例子来理解。

示例 -

输出

The list1 and list2 are equal

说明

在上面的示例中,我们声明了要相互比较的两个列表。我们将这些列表转换为集合,并使用 == 运算符比较每个元素。如果两个列表中的所有元素都相等,则执行 if 块并打印结果。

带 == 运算符的 sort() 方法

Python 的 sort() 函数用于对列表进行排序。如果同一列表中的元素位于同一索引位置,则表示列表相等。

注意 - 在 sort() 方法中,我们可以按任何顺序传递列表项,因为我们在比较之前对列表进行了排序。

让我们理解以下示例 -

示例 -

输出

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

collection.counter() 函数

collection 模块提供了 counter(),可以有效地比较列表。它以字典格式 <值>:<频率> 存储数据,并计算列表中各项的频率。

注意 - 在此函数中,列表元素的顺序无关紧要。

示例 -

输出

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() 函数。

让我们理解下面的例子。

示例 -

输出

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

在本节中,我们介绍了在 Python 中比较两个列表的各种方法。