在python中查找两个列表的所有公共序列
我想在两个列表中找到所有常见的序列。 例如:在python中查找两个列表的所有公共序列,python,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]] match = [[1,2] ,[7,8,9]] 我的代码如下: import difflib def matches(first_string,second_string): s = difflib.SequenceMatcher(No
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]]
match = [[1,2] ,[7,8,9]]
我的代码如下:
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
但我得到的结果是:
matched_list = [[1,2],[7,8,9],[5,6]]
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]]
list1=[1,2]
,list2=[1,2,1,2]
的输出应该是什么?