首页 Python python – 如何找到可能有重复数字的3个列表之间的区别

python – 如何找到可能有重复数字的3个列表之间的区别

参见英文答案 Difference Between Two Lists with Duplicates in Python4个我有3个列表,我想找到第1 /第2和第2 /第3之间的差异并打印出来.这是我的代码:n1 = [1,1,1,2,3] n2 = [1,1,1,2] #

参见英文答案 > Difference Between Two Lists with Duplicates in Python4个
我有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

或使用collections.Counter

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

本文来自网络,不代表云浮站长网立场。转载请注明出处: https://www.0766zz.com/html/kaifa/python/20200906/10136.html
上一篇
下一篇

作者: dawei

【声明】:云浮站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

为您推荐

返回顶部