Python中重复的两个列表之间的区别 [英] Difference Between Two Lists with Duplicates in Python

查看:45
本文介绍了Python中重复的两个列表之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表,其中包含许多相同的项目,包括重复的项目.我想检查第一个列表中的哪些项目不在第二个列表中.例如,我可能有一个这样的列表:

I have two lists that contain many of the same items, including duplicate items. I want to check which items in the first list are not in the second list. For example, I might have one list like this:

l1 = ['a', 'b', 'c', 'b', 'c']

还有一个这样的列表:

l2 = ['a', 'b', 'c', 'b']

比较这两个列表,我想返回这样的第三个列表:

Comparing these two lists I would want to return a third list like this:

l3 = ['c']

我目前正在使用一些我前一段时间编写的糟糕代码,我相当肯定它甚至无法正常工作,如下所示.

I am currently using some terrible code that I made a while ago that I'm fairly certain doesn't even work properly shown below.

def list_difference(l1,l2):
    for i in range(0, len(l1)):
        for j in range(0, len(l2)):
            if l1[i] == l1[j]:
                l1[i] = 'damn'
                l2[j] = 'damn'
    l3 = []
    for item in l1:
        if item!='damn':
            l3.append(item)
    return l3

我怎样才能更好地完成这项任务?

How can I better accomplish this task?

推荐答案

您没有指定顺序是否重要.如果没有,您可以在 >= Python 2.7 中执行此操作:

You didn't specify if the order matters. If it does not, you can do this in >= Python 2.7:

l1 = ['a', 'b', 'c', 'b', 'c']
l2 = ['a', 'b', 'c', 'b']

from collections import Counter

c1 = Counter(l1)
c2 = Counter(l2)

diff = c1-c2
print list(diff.elements())

这篇关于Python中重复的两个列表之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆