Python中具有重复项的两个列表之间的差异

时间:2011-11-12 17:32:56

标签: python

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

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

和一个这样的列表:

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

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

l3 = ['c']

我目前正在使用一些我之前做过的可怕代码,我相当确定它甚至无法正常显示在下面。

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

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

6 个答案:

答案 0 :(得分:28)

您没有说明订单是否重要。如果没有,您可以在> = 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())

答案 1 :(得分:6)

为两个列表创建Counter,然后为另一个列表创建subtract

from collections import Counter

a = [1,2,3,1,2]
b = [1,2,3,1]

c = Counter(a)
c.subtract(Counter(b))

答案 2 :(得分:4)

要考虑重复项和元素的顺序:

from collections import Counter

def list_difference(a, b):
    count = Counter(a) # count items in a
    count.subtract(b)  # subtract items that are in b
    diff = []
    for x in a:
        if count[x] > 0:
           count[x] -= 1
           diff.append(x)
    return diff

Example

print(list_difference("z y z x v x y x u".split(), "x y z w z".split()))
# -> ['y', 'x', 'v', 'x', 'u']

Python 2.5版本:

from collections import defaultdict 

def list_difference25(a, b):
    # count items in a
    count = defaultdict(int) # item -> number of occurrences
    for x in a:
        count[x] += 1

    # subtract items that are in b
    for x in b: 
        count[x] -= 1

    diff = []
    for x in a:
        if count[x] > 0:
           count[x] -= 1
           diff.append(x)
    return diff

答案 3 :(得分:3)

计数器是Python 2.7的新功能。 对于从b中减去a的一般解决方案:

def list_difference(b, a):
    c = list(b)
    for item in a:
       try:
           c.remove(item)
       except ValueError:
           pass            #or maybe you want to keep a values here
    return c

答案 4 :(得分:0)

您可以尝试

list(filter(lambda x:l1.remove(x),li2)) print(l1)

答案 5 :(得分:0)

试试这个:

from collections import Counter
from typing import Sequence

def duplicates_difference(a: Sequence, b: Sequence) -> Counter:
    """
    >>> duplicates_difference([1,2],[1,2,2,3])
    Counter({2: 1, 3: 1})
    """
    shorter, longer = sorted([a, b], key=len)
    return Counter(longer) - Counter(shorter)