我試圖匹配兩個字符串,直到第一個不匹配的字符,然後確定百分比完全匹配。我的代碼是這樣的:匹配兩個字符串(字符到字符),直到第一個不匹配使用python
def match(a, b):
a, b = list(a), list(b)
count = 0
for i in range(len(a)):
if (a[i]!= b[i]): break
else: count = count + 1
return count/len(a)
a = '354575368987943'
b = '354535368987000'
c = '354575368987000'
print(match(a,b)) # return 0.267
print(match(a,c)) # return 0.8
python中是否有任何內置的方法可以做得更快?爲了簡單起見,假設兩個字符串具有相同的長度。
最接近的事情,這是'difflib'的['SequenceMatcher.get_matching_blocks'(https://docs.python.org/2/library/difflib.html#difflib.SequenceMatcher.get_matching_blocks): http://ideone.com/wlUVd9 –
字符串可以作爲列表操作,不需要「列出()」它們。 – TemporalWolf
最好的答案已經在評論中提供給https://stackoverflow.com/questions/18715688/find-common-substring-between-two-strings –