如何在 Python 中比较两个列表(附示例)
比较两个列表是 Python 中最常见的任务之一。你可能需要找出相比昨天的导出新增了哪些用户 ID,检查文件夹里哪些文件被删除了,或者验证某个函数是否返回了预期的值。不过,"比较两个列表"其实可能指好几种不同的需求:
- 哪些元素两个列表都有,哪些只在其中一个里?(交集和差集)
- 两个列表是否相等?(考虑或不考虑顺序)
- 它们具体在哪里不同?(按位置逐个元素比较)
本文用可直接运行的示例讲解以上所有情况,说明各种方法的取舍,最后附一张总结表,帮你选出合适的方法。
只是想快速比较手头的两个列表?把它们粘贴到免费的 两个列表比较工具 中,无需写代码就能看到仅在 A、仅在 B 和两者共有的项目。
1. 使用 set(最常用、最快)
如果你只关心出现了哪些不同的值,而不在乎顺序和重复次数,就用集合。
list_a = [1, 2, 3, 4, 5]
list_b = [4, 5, 6, 7, 8]
set_a = set(list_a)
set_b = set(list_b)
# Common elements (intersection)
print(set_a & set_b) # {4, 5}
# Elements only in A (difference)
print(set_a - set_b) # {1, 2, 3}
# Elements only in B
print(set_b - set_a) # {6, 7, 8}
# Elements in exactly one of the lists (symmetric difference)
print(set_a ^ set_b) # {1, 2, 3, 6, 7, 8}
集合是无序的,所以实际打印的顺序可能和上面注释中的不同。这些运算符都有对应的方法——intersection()、difference() 和 symmetric_difference()——它们可以接受任意可迭代对象,所以 set_a.intersection(list_b) 无需先把 list_b 转换成集合。
优点: 简短、易读、非常快——集合查找的平均时间复杂度是常数级。 缺点: 会丢失原有顺序并去除重复项。元素必须是可哈希的(数字、字符串、元组可以,列表和字典不行)。
2. 列表推导式(保留顺序和重复项)
当 list_a 的顺序很重要,或者需要保留重复项时,使用列表推导式。
list_a = [1, 2, 3, 4, 5, 5] # contains a duplicate
list_b = [4, 5, 6, 7, 8]
set_b = set(list_b) # build once for fast lookups
only_in_a = [x for x in list_a if x not in set_b]
print(only_in_a) # [1, 2, 3]
in_both = [x for x in list_a if x in set_b]
print(in_both) # [4, 5, 5]
一定要对 集合 做成员判断,而不是对列表本身。x in list_b 每次都会扫描整个列表,用这种方式比较两个各有 10 万项的列表需要几十亿次操作;换成集合大约只需要 10 万次查找。
如果既想保留顺序、又想去掉结果中的重复项,可以用 dict.fromkeys(),它会保持插入顺序:
only_in_a_unique = list(dict.fromkeys(x for x in list_a if x not in set_b))
3. 使用 for 循环(便于扩展)
普通循环和列表推导式效果相同,但更容易加入额外的逻辑、日志或输出多个列表。
list_a = ["apple", "Banana", "cherry"]
list_b = ["banana", "date"]
lookup = {item.lower() for item in list_b}
only_in_a, in_both = [], []
for item in list_a:
if item.lower() in lookup: # case-insensitive comparison
in_both.append(item)
else:
only_in_a.append(item)
print(only_in_a) # ['apple', 'cherry']
print(in_both) # ['Banana']
比较前先统一格式(转小写、用 .strip() 去掉空格),是解决"两个列表明明应该匹配却对不上"的最常见方法。
4. collections.Counter(比较各项出现的次数)
当重复次数有意义时使用 Counter——比如把订单列表和发货列表对比,数量也要算在内。
from collections import Counter
list_a = ["a", "b", "b", "c"]
list_b = ["b", "c", "d", "e"]
counter_a = Counter(list_a)
counter_b = Counter(list_b)
# Common elements, using the smaller count of each
print(list((counter_a & counter_b).elements())) # ['b', 'c']
# What is left in A after removing B's items
print(list((counter_a - counter_b).elements())) # ['a', 'b']
结果里保留了第二个 'b',因为 A 中有两个 'b',而 B 中只有一个。
5. 判断两个列表是否相等
== 运算符会按顺序逐个比较元素:
print([1, 2, 3] == [1, 2, 3]) # True
print([1, 2, 3] == [3, 2, 1]) # False – same items, different order
如果要忽略顺序,就根据你对重复项的处理方式选择合适的比较:
from collections import Counter
a = [1, 2, 2, 3]
b = [3, 2, 1, 2]
c = [3, 2, 1]
# Same items with the same counts, any order
print(sorted(a) == sorted(b)) # True
print(Counter(a) == Counter(b)) # True – also works for unsortable items
# Same distinct items, duplicates ignored
print(set(a) == set(c)) # True
print(Counter(a) == Counter(c)) # False – a has two 2s
sorted() 要求元素之间可以互相比较大小;Counter 只要求元素可哈希,而且是线性时间,所以对大列表来说通常是更好的选择。
6. 逐个元素比较两个列表
当位置很重要时——比如测试结果、时间序列、CSV 的两列——用 zip() 成对比较:
expected = [10, 20, 30, 40]
actual = [10, 25, 30, 45]
differences = [
(i, e, a) for i, (e, a) in enumerate(zip(expected, actual)) if e != a
]
print(differences) # [(1, 20, 25), (3, 40, 45)]
zip() 会在较短的列表结束时停止。如果两个列表长度可能不同,用 itertools.zip_longest,多出来的元素也会被报告:
from itertools import zip_longest
a = [1, 2, 3]
b = [1, 2, 3, 4, 5]
extra = [(i, x, y) for i, (x, y) in enumerate(zip_longest(a, b)) if x != y]
print(extra) # [(3, None, 4), (4, None, 5)]
7. 比较字典列表
字典不可哈希,不能直接放进集合。可以改为按唯一键(如 id)来比较:
old = [{"id": 1, "name": "Ann"}, {"id": 2, "name": "Bob"}, {"id": 3, "name": "Cy"}]
new = [{"id": 2, "name": "Bob"}, {"id": 3, "name": "Cyrus"}, {"id": 4, "name": "Dee"}]
old_by_id = {row["id"]: row for row in old}
new_by_id = {row["id"]: row for row in new}
removed = [old_by_id[k] for k in old_by_id.keys() - new_by_id.keys()]
added = [new_by_id[k] for k in new_by_id.keys() - old_by_id.keys()]
changed = [
(old_by_id[k], new_by_id[k])
for k in old_by_id.keys() & new_by_id.keys()
if old_by_id[k] != new_by_id[k]
]
print(removed) # [{'id': 1, 'name': 'Ann'}]
print(added) # [{'id': 4, 'name': 'Dee'}]
print(changed) # [({'id': 3, 'name': 'Cy'}, {'id': 3, 'name': 'Cyrus'})]
字典的键视图(.keys())直接支持集合运算符,所以代码可以写得很简短。如果没有唯一键、需要比较整条记录,可以把每条记录转换成可哈希的形式,例如 tuple(sorted(row.items()))。
8. 大数据:使用 pandas
对于几百万行的数据,或者本来就在 CSV、Excel 文件里的数据,pandas 可以一步标记出每一行是仅在左边、仅在右边还是两边都有:
import pandas as pd
df_a = pd.DataFrame({"email": ["ann@x.com", "bob@x.com", "cy@x.com"]})
df_b = pd.DataFrame({"email": ["bob@x.com", "cy@x.com", "dee@x.com"]})
merged = df_a.merge(df_b, on="email", how="outer", indicator=True)
only_in_a = merged.loc[merged["_merge"] == "left_only", "email"].tolist()
only_in_b = merged.loc[merged["_merge"] == "right_only", "email"].tolist()
in_both = merged.loc[merged["_merge"] == "both", "email"].tolist()
print(only_in_a) # ['ann@x.com']
print(only_in_b) # ['dee@x.com']
print(in_both) # ['bob@x.com', 'cy@x.com']
如果只比较一列,df_a["email"].isin(df_b["email"]) 会返回一个 True/False 掩码,可以直接用来筛选行。比较前先清理关键列(.str.strip().str.lower()),避免格式差异让本该匹配的值对不上。
总结:该用哪种方法?
| 目标 | 最佳方法 | 保留顺序? | 保留重复项? |
|---|---|---|---|
| 找相同 / 不同的元素 | set 运算符 |
否 | 否 |
| 按原顺序找差异 | 列表推导式 + 集合查找 | 是 | 是 |
| 自定义规则(忽略大小写、去空格) | for 循环 + 统一格式的集合 |
是 | 是 |
| 比较每项的出现次数 | collections.Counter |
否 | 是 |
| 两个列表是否完全相同? | ==(有序)或 Counter(任意顺序) |
– | – |
| 按位置找差异 | zip() / zip_longest() |
是 | 是 |
| 字典列表 | 按键建立索引,比较键视图 | – | – |
| 超大或表格数据 | pandas merge(indicator=True) |
– | – |
大多数情况下,先用集合:速度最快,代码也最短。需要保留顺序时换成列表推导式,重复次数有意义时用 Counter,数据太大或本来就是表格时用 pandas。如果只是偶尔比较一次两个列表,在线列表比较工具 几秒钟就能给出答案。