繁体   English   中英

在python中找到两个列表的所有常见序列

[英]find all common sequences of two list in python

我想在两个列表中找到所有常见的序列。 例如:

list1 = [1,2,3,4,5,6,7,8,9]
list2 = [1,2,7,8,9,5,7,5,6]

我希望输出为:

matched_list = [[1,2],[7,8,9],[5,6]]

我的代码如下:

import difflib
def matches(first_string,second_string):
    s = difflib.SequenceMatcher(None, first_string,second_string)
    match = [first_string[i:i+n] for i, j, n in s.get_matching_blocks() if n > 0]
    return match

但是我得到的输出为:

match = [[1,2] ,[7,8,9]]

如果输出顺序不重要,则多遍解决方案可以解决问题。 每次找到匹配项时,都从列表/字符串中删除子字符串/子列表。

履行

def matches(list1, list2):
    while True:
        mbs = difflib.SequenceMatcher(None, list1, list2).get_matching_blocks()
        if len(mbs) == 1: break
        for i, j, n in mbs[::-1]:
            if n > 0: yield list1[i: i + n]
            del list1[i: i + n]
            del list2[j: j + n]

样本输出

>>> list(matches(list1, list2))
[[7, 8, 9], [1, 2], [5, 6]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM