get difference between 3 lists

2019-06-28 04:51发布

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])

How to get difference between 3 sets? For difference of 3 sets, expected output is :

expected output : set([1, 3, 4, 5, 6])

标签: python list set
4条回答
做自己的国王
2楼-- · 2019-06-28 05:04

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])

or:

In [13]: set.union(*l) - set.intersection(*l)
Out[13]: set([1, 3, 4, 5, 6])

(The latter is probably preferable.)

查看更多
Viruses.
3楼-- · 2019-06-28 05:04

What about this:

def difflists(*lists):
    sets = map(set, lists)
    return set.union(*sets) - set.intersection(*sets)

print difflists(a, b, c)    # set([1, 3, 4, 5, 6])

If you want to exclude elements that are present more than once instead:

from itertools import chain
from collections import Counter

def difflists(*lists):
    items = Counter(it for lst in lists for it in lst)
    return [it for it, count in items.iteritems() if count == 1]

print difflists(a, b, c)    # [1, 4, 5, 6]

This methods accept any number of lists

查看更多
Explosion°爆炸
4楼-- · 2019-06-28 05:13

How about this:

>>> a = [1, 2, 3]
>>> b = [2, 4, 5]
>>> c = [3, 2, 6]
>>> z1 = set(a).symmetric_difference(set(b))
>>> z2 = set(b).symmetric_difference(set(c))
>>> print z1.union(z2)
set([1, 3, 4, 5, 6])
查看更多
对你真心纯属浪费
5楼-- · 2019-06-28 05:14

@NPE that answer doesn't work as expected since it relies on the result of the proceeding operations. In your example you can see the '3' overlapping from the first to the third but still being included in the result.

>>> a = set(('a','b','c')) 
>>> b = set(('c','d','e'))
>>> c = set(('e','f','g'))
>>> (a | b | c) - (a & b & c)
set(['a', 'c', 'b', 'e', 'd', 'g', 'f'])

This happens because it does the intersection of 'a' to 'b' and then the intersection to 'c'. To fix this you could:

>>> (a | b | c) - ((a & b) | (a & c) | (b & c))
set(['a', 'b', 'd', 'g', 'f'])

Also to save two operations you could get the the symmetric difference of two, union with the third, then do the difference of the union of the intersections of the first and third and second and third.

>>> ((a ^ b) | c) - ((a & c) | (b & c))
set(['a', 'b', 'd', 'g', 'f'])
查看更多
登录 后发表回答