0

我试图在两个字符串列表之间找到一个差异(最长的公共子序列)。我猜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 方式吗?

4

3 回答 3

2

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

例子 -

>>> l1 = [1,2,3,4,5]
>>> l2 = [4,5,6,7,8]
>>> print(list(set(l1) - set(l2)))
[1, 2, 3]
于 2015-06-23T08:29:14.723 回答
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]: 
于 2015-06-23T08:38:41.740 回答
-2
l1 = ["a", "b", "c"]

l2 = ["a", "b", "d"]

如果我们想获取 l2 ("d") 中不存在的项目,请尝试以下代码

l3 = [i for i in l1 if i not in l2]

# l3 now == ["c"]
于 2021-09-28T12:24:52.760 回答