Best algorithm to compare two lists in python

时间秒杀一切 提交于 2020-01-23 14:33:24

问题


I have two lists (list1 and list2) in python filled with an own datatype. I want to compare these to lists and give all elements of these lists to stdout(or somewhere else), but in a specific order(without sorting the lists in any way).

List1 and List2 can have elements which are not in the other list, but can also have elements which be in the other list. These elements, beeing in both lists, should output at the same line. But the elements beeing only in one list, should be in the right order too, at the end.

Example:

List1 = [A,B,C,D,F,H,G];
List2 = [A,C,D,E,H];

output should be:

List1 |List2
  A      A
  B      
  C      C
  D      D
         E
  F
  H      H
  G

How can I "sort" in these way?


回答1:


import difflib, re

list_a = ['A', 'B', 'C', 'D', 'F', 'H', 'G']
list_b = ['A', 'C', 'D', 'E', 'H']

for i in difflib.Differ().compare(list_a, list_b):
    differ_char, letter = re.match(r'([\s\-+]) ([A-Z])', i).groups()
    choices = ['  ' + letter, letter + '  ', letter + ' ' + letter]
    print choices[['+', '-', ' '].index(differ_char)] # print lines



回答2:


You should use difflib.SequenceMatcher instead of difflib.Differ if you want to align something else than strings.

import difflib
def align(a, b):
    return sum((zip(a[i1:i2], b[j1:j2]) if tag == 'equal' 
                  else map(None, a[i1:i2], []) + map(None, [], b[j1:j2])
                        for tag, i1, i2, j1, j2 
                        in difflib.SequenceMatcher(None, a, b).get_opcodes()), [])

Example with integers:

list_a = [1, 2,    4, 5,    7]
list_b = [1, 2, 3, 4,    6, 7]

for (a,b) in align(list_a, list_b):
    print '{0:^5}|{1:^5}'.format(a or '',b or '')

Results:

  1  |  1  
  2  |  2  
     |  3  
  4  |  4  
  5  |     
     |  6  
  7  |  7  



回答3:


A simple way to do this.

List1 = ['A','B','C','D','F','H','G']
List2 = ['A','C','D','E','H']

List3 = set(List1 + List2)
for i in sorted(List3, key=lambda item: item):
    if i in List1 and i in List2:
            print('{0} | {0}'.format(i))
    elif i in List1:
        print('{0} | '.format(i))
    elif i in List2:
        print('  | {0}'.format(i))

A | A
B | 
C | C
D | D
  | E
F | 
G | 
H | H


来源:https://stackoverflow.com/questions/29675480/best-algorithm-to-compare-two-lists-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!