在 Python 中检查两个列表是否相同

pythonserver side programmingprogramming更新于 2025/12/27 9:16:17

在 Python 数据分析中,我们可能会遇到需要比较两个列表并确定它们是否相同(即是否具有相同元素)的情况。

示例

listA = ['Mon','Tue','Wed','Thu']
listB = ['Mon','Wed','Tue','Thu']
# 给定列表
print("Given listA: ",listA)
print("Given listB: ",listB)
# Sort the lists
listA.sort()
listB.sort()

# 检查是否相等
if listA == listB:
   print("Lists are identical")
else:
   print("Lists are not identical")

输出

运行上述代码得到以下结果 −

Given listA: ['Mon', 'Tue', 'Wed', 'Thu']
Given listB: ['Mon', 'Wed', 'Tue', 'Thu']
Lists are identical

使用 Counter

collections 模块中的 Counter 函数可以帮助我们找到列表中每个项目的出现次数。在下面的例子中,我们还取两个重复元素。如果两个列表中每个元素的频率相等,则我们认为列表是相同的。

示例

import collections
listA = ['Mon','Tue','Wed','Tue']
listB = ['Mon','Wed','Tue','Tue']
# 给定列表
print("Given listA: ",listA)
print("Given listB: ",listB)
# 检查是否相等
if collections.Counter(listA) == collections.Counter(listB):
   print("Lists are identical")
else:
   print("Lists are not identical")

# 再次检查
listB = ['Mon','Wed','Wed','Tue']
print("Given listB: ",listB)

# 检查是否相等
if collections.Counter(listA) == collections.Counter(listB):
   print("Lists are identical")
else:
   print("Lists are not identical")

输出

运行上述代码得到以下结果 −

Given listA: ['Mon', 'Tue', 'Wed', 'Tue']
Given listB: ['Mon', 'Wed', 'Tue', 'Tue']
Lists are identical
Given listB: ['Mon', 'Wed', 'Wed', 'Tue']
Lists are not identical

相关文章


有用资源