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])
In your example you can see the '3' overlapping from the first to the third but still being included in the result. 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.
The difference between two lists (say list1 and list2) can be found using the following simple function. By Using the above function, the difference can be found using diff(temp2, temp1) or diff(temp1, temp2) . Both will give the result ['Four', 'Three'] .
Use set. symmetric_difference() to Find the Difference Between Two Lists in Python. Here, the set() method is used to convert both the lists into sets initially. The symmetric_difference() method is used to return the elements that are either in the first set or in the second set.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With