加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 23:46:41 所属栏目:Python 来源:网络整理
导读:参见英文答案 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"

参见英文答案 > 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

或使用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})

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读