You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中两个列表的差异处理:获取交集及各自独有元素

用Python集合处理列表的交集与差集

这事儿用Python的集合来处理最顺手,集合天生就擅长解决这种找共同元素、独有元素的问题,直接看具体实现:

你的原始列表:

list1 = ['a','b','c','d']
list2 = ['a','e','f','b','g']

完整实现代码

# 先把列表转成集合,集合支持交集、差集这类运算
set1 = set(list1)
set2 = set(list2)

# 同时存在于两个列表的元素(交集)
in_both = list(set1 & set2)
# 也可以用方法调用:in_both = list(set1.intersection(set2))

# 只在list1里有的元素(set1相对set2的差集)
only_in_list1 = list(set1 - set2)
# 等价写法:only_in_list1 = list(set1.difference(set2))

# 只在list2里有的元素(set2相对set1的差集)
only_in_list2 = list(set2 - set1)
# 等价写法:only_in_list2 = list(set2.difference(set1))

# 查看结果
print("in_both =", in_both)
print("only_in_list1 =", only_in_list1)
print("only_in_list2 =", only_in_list2)

简单解释

  • &(或intersection()):找两个集合的交集,也就是两边都有的元素
  • -(或difference()):找差集,比如set1 - set2就是只属于set1、不属于set2的元素
  • 最后把集合转回列表,就得到你要的格式了

内容的提问来源于stack exchange,提问作者Georgia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 20:34:53