Difference Between Two Lists with Duplicates in Python

后端 未结 5 1203
灰色年华
灰色年华 2020-11-30 06:09

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 mig

5条回答
  •  南方客
    南方客 (楼主)
    2020-11-30 06:26

    To take into account both duplicates and the order of elements:

    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 version:

    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
    

提交回复
热议问题