比较python中两个列表的最佳算法 [英] Best algorithm to compare two lists in python

查看:279
本文介绍了比较python中两个列表的最佳算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有两个列表(list1和list2),其中填充了自己的数据类型. 我想将它们与列表进行比较,并将这些列表的所有元素提供给stdout(或其他位置),但要以特定的顺序进行(不以任何方式对列表进行排序).

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和List2可以具有不在另一个列表中的元素,但是也可以具有在另一个列表中的元素.这些元素(在两个列表中都出现)应在同一行输出.但是,只在一个列表中列出的元素最后也应该以正确的顺序排列.

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.

示例:

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?

推荐答案

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

这篇关于比较python中两个列表的最佳算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆