![](/img/trans.png)
[英]Python code to find the sum of common elements in two sequences of integers in a range
[英]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.