Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get difference between 3 lists

Tags:

python

list

set

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])
like image 755
sam Avatar asked Aug 15 '14 09:08

sam


People also ask

How do you find the difference between three lists in Python?

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.

How do you find the difference in lists?

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'] .

How do you find the absolute difference between two lists in Python?

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.


1 Answers

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

like image 92
NPE Avatar answered Nov 02 '22 23:11

NPE