有人可以解释一下get_matching_blocks()的行为吗? 对于以下示例:
string2 = "1234 abc efg"
string1 = "efg abc 1234"
match = SequenceMatcher(None, string1, string2).get_matching_blocks()
print(match)
它返回以下结果
[Match(a=3, b=4, size=5), Match(a=12, b=12, size=0)]
意思是它只找到子序列“abc”
为什么不返回子序列“1234”和“efg”?
答案 0 :(得分:1)
According to the documenatation:
返回描述匹配子序列的三元组列表。每个三元组的形式为(i,j,n),并且意味着a [i:i + n] == b [j:j + n]。三元组在i和j中单调递增。
这里的关键词是"单调增加"。这意味着,如果返回的列表包含三元组t = (i, j, n)
和t' = (i', j', n')
,其中t
出现在t'
之前,那么我们必须i <= j <= i' <= j'
。
答案 1 :(得分:1)
文档说“三元组在i和j中单调增加。”因此,在找到匹配后,实现将永远不会倒退。它找到“abc”并且只从那里向前看每个字符串。