Python实现两个list求交集,并集,差集的方法示例
作者:bitcarmanlee 时间:2021-12-27 19:52:06
本文实例讲述了Python实现两个list求交集,并集,差集的方法。分享给大家供大家参考,具体如下:
在python中,数组可以用list来表示。如果有两个数组,分别要求交集,并集与差集,怎么实现比较方便呢?
当然最容易想到的是对两个数组做循环,即写两个for循环来实现。这种写法大部分同学应该都会,而且也没有太多的技术含量,本博主就不解释了。这里给大家使用更为 * ility的一些方法。
老规矩,talk is cheap,show me the code
#!/usr/bin/env python
#coding:utf-8
'''
Created on 2016年6月9日
@author: lei.wang
'''
def diff(listA,listB):
#求交集的两种方式
retA = [i for i in listA if i in listB]
retB = list(set(listA).intersection(set(listB)))
print "retA is: ",retA
print "retB is: ",retB
#求并集
retC = list(set(listA).union(set(listB)))
print "retC1 is: ",retC
#求差集,在B中但不在A中
retD = list(set(listB).difference(set(listA)))
print "retD is: ",retD
retE = [i for i in listB if i not in listA]
print "retE is: ",retE
def main():
listA = [1,2,3,4,5]
listB = [3,4,5,6,7]
diff(listA,listB)
if __name__ == '__main__':
main()
让code run起来
retA is: [3, 4, 5]
retB is: [3, 4, 5]
retC1 is: [1, 2, 3, 4, 5, 6, 7]
retD is: [6, 7]
retE is: [6, 7]
结合代码来看,大体上是两种思路:
1.使用列表解析式。列表解析式一般来说比循环更快,而且更pythonic显得更牛逼。
2.将list转成set以后,使用set的各种方法去处理。
希望本文所述对大家Python程序设计有所帮助。
来源:https://blog.csdn.net/bitcarmanlee/article/details/51622263
标签:Python,list,交集
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
用Python抢过年的火车票附源码
2021-11-12 00:01:42
![](https://img.aspxhome.com/file/2023/2/93572_0s.gif)
python计算机视觉opencv卡号识别示例详解
2023-04-14 13:58:25
![](https://img.aspxhome.com/file/2023/6/105306_0s.png)
PyTorch中clone()、detach()及相关扩展详解
2022-06-29 17:50:34
css布局自适应高度方法
2007-05-11 17:03:00
详解Python中的Dict(下篇)
2021-11-10 17:16:14
![](https://img.aspxhome.com/file/2023/0/90920_0s.png)
好习惯和坏习惯
2009-01-20 12:51:00
详解Python中dict与set的使用
2022-09-11 05:22:22
概述javascript在Google IE中的调试技巧
2023-08-08 11:50:29
![](https://img.aspxhome.com/file/2023/8/55928_0s.jpg)
python读取txt数据的操作步骤
2022-12-27 10:36:31
![](https://img.aspxhome.com/file/2023/2/97102_0s.png)
利用XMLBean轻轻松松读写XML
2008-09-04 11:25:00
Http头 Range、Content-Range
2010-06-25 19:19:00
通过mod_python配置运行在Apache上的Django框架
2021-07-09 17:54:45
Python数据分析之 Matplotlib 折线图绘制
2023-12-05 02:18:13
![](https://img.aspxhome.com/file/2023/2/83902_0s.webp)
AI与Python人工智能启发式搜索概念理解
2021-08-05 03:56:28
P3P 和 跨域 (cross-domain) cookie 访问(读取和设置)
2011-04-02 10:42:00
js 轮播效果实例分享
2023-07-16 00:42:43
基于Python实现简易学生信息管理系统
2021-04-07 23:19:49
![](https://img.aspxhome.com/file/2023/4/82774_0s.jpg)
SQL参数化查询的另一个理由 命中执行计划
2012-08-21 10:31:16
Win10系统下Pytorch环境的搭建过程
2023-09-29 06:57:54
![](https://img.aspxhome.com/file/2023/1/112371_0s.png)
Python多线程编程之多线程加锁操作示例
2023-11-01 00:37:19