查找两个字符串列表的差异

时间:2015-06-23 08:27:22

标签: python diff difflib

我试图在两个字符串列表之间找到diff(最长的公共子序列)。我猜这里difflib可能很有用,但difflib.ndiff使用-+等注释输出。例如

from difflib import ndiff
t1 = 'one 1\ntwo 2\nthree 3'.splitlines()
t2 = 'one 1\ntwo 29\nthree 3'.splitlines()
d = list(ndiff(t1, t2    )); print d;

['  one 1', '- two 2', '+ two 29', '?      +\n', '  three 3']

以正确的方式标记并删除输出中的字母代码?这是差异列表的Pythonic方法吗?

2 个答案:

答案 0 :(得分:0)

如果你想要的只是第一个列表与第二个列表的区别,你可以将它们转换为set并使用-运算符进行设置差异。

示例 -

>>> l1 = [1,2,3,4,5]
>>> l2 = [4,5,6,7,8]
>>> print(list(set(l1) - set(l2)))
[1, 2, 3]

答案 1 :(得分:0)

按列表理解:

In [16]: l1 = ['a', 'b', 'c', 'd']

In [17]: l2 = ['a', 'x', 'y', 'c']

In [18]: l1_l2 = [ii for ii in l1 if ii not in l2]

In [19]: l1_l2
Out[19]: ['b', 'd']

In [20]: l2_l1 = [ii for ii in l2 if ii not in l1]

In [21]: l2_l1 
Out[21]: ['x', 'y']

In [22]: