发布时间:2019-08-17 09:07:41编辑:auto阅读(2764)
在python3对列表的处理中,会经常使用到Python求两个list的差集、交集与并集的方法。
下面就以实例形式对此加以分析。
如有下面两个数组:
a = [1,2,3]
b = [2,3]
想要的结果是[1]
下面记录一下三种实现方式:
1. 正常的方式
ret = []
for i in a:
if i not in b:
ret.append(i)
2.简化版
ret = [ i for i in a if i not in b ]
3.高级版
ret = list(set(a) ^ set(b))
4.最终版
print (list(set(b).difference(set(a)))) # b中有而a中没有的
print (list(set(a).union(set(b))))
print (list(set(a).intersection(set(b))))
上一篇: Python中各个模块的介绍和使用
下一篇: linux多个python版本共存切换方
54474
41254
35795
31319
26223
25936
24437
20006
16015
15450
2366°
2157°
2248°
2376°
2332°
2544°
2490°
2313°
2380°
2356°