get difference between 3 lists

萝らか妹 提交于 2019-12-14 04:17:26

问题


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

回答1:


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




回答2:


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



回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/25324136/get-difference-between-3-lists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!