在工作中,经常会碰到对两个list比较的问题,一般的需求是求其两个中不同的元素、求其并集或者求其交集。为了快速完成代码,现将例子记录如下。
总体策略:运用set()函数,该函数是创建一个无序不重复元素集,可进行关系测试,可删除重复数据,还可以机选交集、差集、并集等。在碰到上述需求时,都可将其转化为set
1、求两个list中不同的元素
a = ['123','456','789']
b = ['123','789','234']
diff = list(set(a)^set(b))
如果两个list其中一个是另一个的子集,可直接用以下代码
a = ['123','456','789']
b = ['123','456']
diff = list(set(a)-set(b))
2、求两个list中的交集
a = ['123','456','789']
b = ['123','789','234']
diff = list(set(a)&set(b))
a = ['123','456','789']
b = ['123','789','234']
union = list(set(a) | set(b))