得到3个列表之间的差异 [英] get difference between 3 lists
本文介绍了得到3个列表之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在处理列表的差异.
I am working on differences of lists.
>>a = [1, 2, 3]
>>b = [2, 4, 5]
>>c = [3, 2, 6]
两组之间的对称性差异可以使用:
Symmetric difference between 2 sets can be done using:
>>z = set(a).symmetric_difference(set(b))
>>print z
>>set([1, 3, 4, 5])
如何获得3套之间的差异? 对于3套的差异,预期输出为:
How to get difference between 3 sets? For difference of 3 sets, expected output is :
expected output : set([1, 3, 4, 5, 6])
推荐答案
只需从并集中减去交集即可:
Just subtract the intersection from the union:
In [1]: a = set([1, 2, 3])
In [2]: b = set([2, 4, 5])
In [3]: c = set([3, 2, 6])
In [4]: (a | b | c) - (a & b & c)
Out[4]: set([1, 3, 4, 5, 6])
或者,归纳为任意集合集:
Or, to generalise to an arbitrary collection of sets:
In [10]: l = [a, b, c]
In [11]: reduce(set.union, l) - reduce(set.intersection, l)
Out[11]: set([1, 3, 4, 5, 6])
或:
In [13]: set.union(*l) - set.intersection(*l)
Out[13]: set([1, 3, 4, 5, 6])
(后者可能更可取.)
这篇关于得到3个列表之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文