参见英文答案 > Difference Between Two Lists with Duplicates in Python 4个
我有3个列表,我想找到第1 /第2和第2 /第3之间的差异
并打印出来.
这是我的代码:
n1 = [1,1,2,3]
n2 = [1,2] # Here the 3 is not found ("3" is not present in n1 at all)
n3 = [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
但我得到的输出只有3.
如何使它输出1和3?我也尝试使用套装,但它只打印了3次.
最佳答案
由于您似乎关心在两个列表中找到项目的次数,您需要从您要比较的列表中删除匹配的项目:
comp = n2[:] # make a copy
for x in n1:
if x not in comp:
print x
else:
comp.remove(x)
# output: 3
from collections import Counter
print Counter(n1) - Counter(n2)
# output: Counter({3: 1})
它告诉你n1中哪些项不在n2中,或者在n1中比在n2中更常见.
所以,例如:
>>> Counter([1,3]) - Counter([1,2])
Counter({2: 2,3: 1})