How to find the difference between 3 lists that may have duplicate numbers

I have 3 lists and I want to find the difference between 1st / 2nd and 2nd / 3rd and print them.

Here is my code:

n1 = [1,1,1,2,3] n2 = [1,1,1,2] # Here the 3 is not found ("3" is not present in n1 at all) n3 = [1,1,2] # here 1 is not found (there are fewer "1"s in n3 than in n2) for x in n1: if x not in n2: print x for m in n2: if m not in n3: print m 

but I get only 3 as output.

How to conclude 1 and 3? I tried using set , but it printed 3 again.

+5
source share
2 answers

Since you seem to care about how many times the item was found in both lists, you need to either remove matching items from the list that you are comparing:

 comp = n2[:] # make a copy for x in n1: if x not in comp: print x else: comp.remove(x) # output: 3 

or use collections.Counter

 from collections import Counter print Counter(n1) - Counter(n2) # output: Counter({3: 1}) 

which tells you which elements in n1 not in n2 , or they can be found more often in n1 than in n2 .

So for example:

 >>> Counter([1,2,2,2,3]) - Counter([1,2]) Counter({2: 2, 3: 1}) 
+6
source

you can use set to find the difference between the list.

 print set(n1).difference(set(n2)) 
-3
source

Source: https://habr.com/ru/post/1234862/


All Articles