使用 Python 获取两个列表的交集、并集、差集的常用方法
来源:互联网 发布:步惊云软件 编辑:程序博客网 时间:2024/06/06 04:59
之前想求两个list的差集 用了 下面方法 结果特别慢
# # print(len(set(i for i in a if i not in b)))
网上看到一篇好博客 分享一下
在数据处理中经常需要使用 Python 来获取两个列表的交集,并集和差集。在 Python 中实现的方法有很多,我平时只使用一两种我所熟悉的,但效率不一定最高,也不一定最优美,所以这次想把常用的方法都搜集总结一下。
交集(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 慢了非常非常多。
参考资料:
- Python - Intersection of two lists
- How to find list intersection?
- List intersection in python: let’s do it quickly
- python 求两个list的差集,并集和交集
并集(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 慢了非常非常多。
参考资料:
- Python set Union and set Intersection operate differently?
- How to find the intersection and union of two lists in Python
- python 求两个list的差集,并集和交集
差集(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 adifference = 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 adifference = 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 adifference = [x for x in b if x not in set(a)] # elements in a but not in b
注意:如果不考虑顺序并且一定要使用 loop 的话,不要直接使用 List,而应该使用 Set。在 List 中查找元素相对 Set 慢了非常非常多。
参考资料:
- Get difference between two lists
- Retaining order while using Python’s set difference
- How to find the intersection and union of two lists in Python
- python 求两个list的差集,并集和交集
阅读全文
0 0
- 使用 Python 获取两个列表的交集、并集、差集的常用方法
- Python -- 两个列表的差集、并集和交集
- python两个 list 获取交集,并集,差集的方法.
- python两个 list 获取交集,并集,差集的方法
- python两个 list 获取交集,并集,差集的方法.
- python两个 list 获取交集,并集,差集的方法
- python两个 list 获取交集,并集,差集的方法
- python两个 list 获取交集,并集,差集的方法
- python两个 list 获取交集,并集,差集的方法.
- 两个集合的交集,并集,差
- Python求两个list的差集、交集与并集的方法
- Python求两个list的差集、交集与并集的方法
- Python求两个list的差集、交集与并集的方法(转)
- python获得两个数组交集、并集、差集的方法
- 获取两个DataTable之间的差集、交集、并集集合(Except、Intersect、Union)
- 获取两个DataTable之间的差集、交集、并集集合(Except、Intersect、Union)
- 【mysql】mysql获取两个集合的交集/差集/并集
- uniq 求两个文件的交集,并集,差集
- iframe高度自适应
- ubuntu清除多余内核
- 有机聚硅氮烷 IOTA 9118
- Tableau 气泡图+日历图
- 安卓专项测试之GPU测试探索
- 使用 Python 获取两个列表的交集、并集、差集的常用方法
- UVA1599IdealPath
- JAVA Web.xml 加载顺序
- Red5安装与使用
- rm命令
- NSMutableArray的创建方法
- $.ajax()方法参数详解
- listview的优化
- delphi chrome cef3 控件学习笔记 (二)