使用 Python 获取两个列表的交集、并集、差集的常用方法

本文介绍了如何使用Python高效地处理列表运算,包括求交集、并集和差集等常见操作。文章对比了几种不同的方法,并提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前想求两个list的差集 用了 下面方法 结果特别慢
# # print(len(set(i for i in a if i not in b)))
网上看到一篇好博客 分享一下

在数据处理中经常需要使用 Python 来获取两个列表的交集,并集和差集。在 Python 中实现的方法有很多,我平时只使用一两种我所熟悉的,但效率不一定最高,也不一定最优美,所以这次想把常用的方法都搜集总结一下。

intersection-union-differenceintersection-union-difference

交集(Intersection)

>>> a = [1, 2, 3, 4, 5, 6]
>>> b = [2, 4, 6, 8 ,10]
>>> a and b
[2, 4, 6]

方法一:

intersection = list(set(a).intersection(b))

方法二:

intersection = list(set(a) & set(b))

方法三:

intersection = [x for x in b if x in set(a)]   # list a is the larger list b

方法四:

intersection = list((set(a).union(set(b)))^(set(a)^set(b)))

注意:如果不考虑顺序并且一定要使用 loop 的话,不要直接使用 List,而应该使用 Set。在 List 中查找元素相对 Set 慢了非常非常多。

参考资料:

并集(Union)

>>> a = [1, 2, 3, 4, 5, 6]
>>> b = [2, 4, 6, 8 ,10]
>>> a or b
[1, 2, 3, 4, 5, 6, 8, 10]

方法一:

union = list(set(a) | set(b))

方法二:

list(set(a).union(set(b)))

注意:如果不考虑顺序并且一定要使用 loop 的话,不要直接使用 List,而应该使用 Set。在 List 中查找元素相对 Set 慢了非常非常多。

参考资料:

差集(Difference Set)

>>> a = [1, 2, 3, 4, 5, 6]
>>> b = [2, 4, 6, 8 ,10]
>>> a or b
[1, 2, 3, 4, 5, 6, 8, 10]

方法一:

difference = list(set(b).difference(set(a)))    # elements in b but not in a
difference = list(set(a).difference(set(b)))    # elements in a but not in b

方法二:

difference = list(set(a_list)^set(b_list))

方法三:

difference = list(set(a)-set(b))    # elements in b but not in a
difference = list(set(a)-set(b))    # elements in a but not in b

方法四:

difference = [x for x in b if x not in set(a)]    # elements in b but not in a
difference = [x for x in b if x not in set(a)]    # elements in a but not in b

注意:如果不考虑顺序并且一定要使用 loop 的话,不要直接使用 List,而应该使用 Set。在 List 中查找元素相对 Set 慢了非常非常多。

参考资料:


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值