Create a complement of list preserving duplicate values

前端 未结 5 1467
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-11 01:32

Given list a = [1, 2, 2, 3] and its sublist b = [1, 2] find a list complementing b in such a way that sorted(a) == sorted(b + complement)

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-11 01:39

    If the order of elements in the complement doesn't matter, then collections.Counter is all that is needed:

    from collections import Counter
    
    a = [1, 2, 3, 2]
    b = [1, 2]
    
    complement = list((Counter(a) - Counter(b)).elements())  # complement = [2, 3]
    

    If the order of items in the complement should be the same order as in the original list, then use something like this:

    from collections import Counter, defaultdict
    from itertools import count
    
    a = [1,2,3,2]
    b = [2,1]
    
    c = Counter(b)
    d = defaultdict(count)
    
    complement = [x for x in a if next(d[x]) >= c[x]]  # complement = [3, 2]
    

提交回复
热议问题