美文网首页Python基础
Python3:求两个list的差集、并集与交集

Python3:求两个list的差集、并集与交集

作者: 极客与宽客 | 来源:发表于2019-04-01 17:59 被阅读2次

在python3对列表的处理中,会经常使用到Python求两个list的差集、交集与并集的方法。

一.两个list差集

如有下面两个数组:

a = [1,2,3]

b = [2,3]

想要的结果是[1]

下面记录一下三种实现方式:

1. 正常的方式

ret = []

foriina:

ifinotinb:

        ret.append(i)

2.简化版

ret = [ iforiinaifinotinb ]

3.高级版

ret = list(set(a) ^ set(b))

4.最终版

printlist(set(b).difference(set(a)))# b中有而a中没有的

二.两个list并集

printlist(set(a).union(set(b)))

三.两个list交集

printlist(set(a).intersection(set(b)))

参考资料:http://www.cnblogs.com/jlf0103/p/8882896.html

相关文章

网友评论

    本文标题:Python3:求两个list的差集、并集与交集

    本文链接:https://www.haomeiwen.com/subject/pmttmqtx.html