如何找到可能包含重复数字的3个列表之间的差异

use*_*690 5 python python-2.7

我有3个列表,我想找到第1 /第2和第2 /第3之间的差异并打印它们.

这是我的代码:

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 
Run Code Online (Sandbox Code Playgroud)

但我得到的输出只有3.

如何使它输出1和3?我也尝试使用sets,但它只是3再次打印.

Tim*_*ker 6

由于您似乎关心在两个列表中找到项目的次数,您需要从您要比较的列表中删除匹配的项目:

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

或使用 collections.Counter

from collections import Counter
print Counter(n1) - Counter(n2)
# output: Counter({3: 1})
Run Code Online (Sandbox Code Playgroud)

它告诉你这项目n1是不是在n2或可以更经常发现n1n2.

所以,例如:

>>> Counter([1,2,2,2,3]) - Counter([1,2])
Counter({2: 2, 3: 1})
Run Code Online (Sandbox Code Playgroud)