Python实现两个list求交集,并集,差集的方法示例

yipeiwu_com6年前Python基础

本文实例讲述了Python实现两个list求交集,并集,差集的方法。分享给大家供大家参考,具体如下:

在python中,数组可以用list来表示。如果有两个数组,分别要求交集,并集与差集,怎么实现比较方便呢?

当然最容易想到的是对两个数组做循环,即写两个for循环来实现。这种写法大部分同学应该都会,而且也没有太多的技术含量,本博主就不解释了。这里给大家使用更为装bility的一些方法。

老规矩,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相关内容可查看本站专题:《Python列表(list)操作技巧总结》、《Python字符串操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Windows下的Python 3.6.1的下载与安装图文详解(适合32位和64位)

Windows下的Python 3.6.1的下载与安装图文详解(适合32位和64位)

为什么,这么简单的一个python,我还要特意来写一篇文章呢? 是因为留念下,在使用了Anaconda2和Anaconda3的基础上,现在需安装python3.6.0来做数据分析。...

windows下Virtualenvwrapper安装教程

windows下Virtualenvwrapper安装教程

windows下安装Virtualenvwrapper 我们可以使用Virtualenvwrapper来方便地管理python虚拟环境,但是在windows上安装的时候.....直接 i...

Python3.6使用tesseract-ocr的正确方法

Tesseract介绍 tesseract是一个挺不错的OCR引擎,目前的问题是最新的中文资料相对较少,过时、不准确的信息偏多。 tesseract是一个google支持的开源ocr项目...

在matplotlib的图中设置中文标签的方法

在matplotlib的图中设置中文标签的方法

其实就是通过 FontProperties来设置的,请参考以下代码: import matplotlib.pyplot as plt from matplotlib.font_man...

Python随机数random模块使用指南

random 模块是Python自带的模块,除了生成最简单的随机数以外,还有很多功能。 random.random() 用来生成一个0~1之间的随机浮点数,范围[0,10 >...