Get difference between two lists

前端 未结 27 2844
傲寒
傲寒 2020-11-21 11:36

I have two lists in Python, like these:

temp1 = [\'One\', \'Two\', \'Three\', \'Four\']
temp2 = [\'One\', \'Two\']

I need to create a third

27条回答
  •  情深已故
    2020-11-21 11:53

    if you want something more like a changeset... could use Counter

    from collections import Counter
    
    def diff(a, b):
      """ more verbose than needs to be, for clarity """
      ca, cb = Counter(a), Counter(b)
      to_add = cb - ca
      to_remove = ca - cb
      changes = Counter(to_add)
      changes.subtract(to_remove)
      return changes
    
    lista = ['one', 'three', 'four', 'four', 'one']
    listb = ['one', 'two', 'three']
    
    In [127]: diff(lista, listb)
    Out[127]: Counter({'two': 1, 'one': -1, 'four': -2})
    # in order to go from lista to list b, you need to add a "two", remove a "one", and remove two "four"s
    
    In [128]: diff(listb, lista)
    Out[128]: Counter({'four': 2, 'one': 1, 'two': -1})
    # in order to go from listb to lista, you must add two "four"s, add a "one", and remove a "two"
    

提交回复
热议问题