今天爱分享给大家带来Python 如何求两个列表(list)的交集、差集或并集?【面试题详解】,希望能够帮助大大家。
求两个列表(list)的交集、差集或并集,最容易想到的方法就是用 for 循环来实现,如下所示:
a = [1, 2, 3, 4, 5]
b = [2, 4, 5, 6, 7]
# 交集
result = [r for r in a if r in b]
print(f"a与b的交集: {result}") # a与b的交集: [2, 4, 5]
# 差集 在a中但不在b中
result = [r for r in a if r not in b]
print(f"a与b的差集: {result}") # a与b的差集: [1, 3]
# 并集
result = a
for r in b:
if r not in result:
result.append(r)
print(f"a与b的并集: {result}") # a与b的并集: [1, 2, 3, 4, 5, 6, 7]
方法二:用 set 澡作
a = [1, 2, 3, 4, 5] b = [2, 4, 5, 6, 7] # 交集 result = list(set(a).intersection(set(b))) print(f"a与b的交集: ", result) # a与b的交集: [2, 4, 5] # 差集 在a中但不在b中 result = list(set(a).difference(set(b))) print(f"a与b的差集: ", result) # a与b的差集: [1, 3] # 并集 result = list(set(a).union(set(b))) print(f"a与b的并集: ", result) # a与b的并集: [1, 2, 3, 4, 5, 6, 7]
原文链接:https://blog.itblood.com/1491.html,转载请注明出处。

![荒诞的诱惑0.06官中汉化版[PC+安卓/2.42G/更新] [国产SLG/首发/沙盒]](/wp-content/uploads/replace/2025/10/04/804dd71fcdc26b381de05992680d8e2b.webp)