Get difference between two lists

前端 未结 27 2850
傲寒
傲寒 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:42

    I wanted something that would take two lists and could do what diff in bash does. Since this question pops up first when you search for "python diff two lists" and is not very specific, I will post what I came up with.

    Using SequenceMather from difflib you can compare two lists like diff does. None of the other answers will tell you the position where the difference occurs, but this one does. Some answers give the difference in only one direction. Some reorder the elements. Some don't handle duplicates. But this solution gives you a true difference between two lists:

    a = 'A quick fox jumps the lazy dog'.split()
    b = 'A quick brown mouse jumps over the dog'.split()
    
    from difflib import SequenceMatcher
    
    for tag, i, j, k, l in SequenceMatcher(None, a, b).get_opcodes():
      if tag == 'equal': print('both have', a[i:j])
      if tag in ('delete', 'replace'): print('  1st has', a[i:j])
      if tag in ('insert', 'replace'): print('  2nd has', b[k:l])
    

    This outputs:

    both have ['A', 'quick']
      1st has ['fox']
      2nd has ['brown', 'mouse']
    both have ['jumps']
      2nd has ['over']
    both have ['the']
      1st has ['lazy']
    both have ['dog']
    

    Of course, if your application makes the same assumptions the other answers make, you will benefit from them the most. But if you are looking for a true diff functionality, then this is the only way to go.

    For example, none of the other answers could handle:

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

    But this one does:

      2nd has [5, 4, 3, 2]
    both have [1]
      1st has [2, 3, 4, 5]
    

提交回复
热议问题