使用Python逐个匹配两个字符串(按字符匹配),直到第一个不匹配的字符。

4
我正在尝试逐个匹配两个字符串,直到第一个不匹配的字符,并确定百分比的完全匹配度。我的代码如下所示:
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中是否已经内置了可更快地执行此操作的方法? 为简单起见,假设这两个字符串具有相同的长度。


最接近此功能的是 difflibSequenceMatcher.get_matching_blocks:http://ideone.com/wlUVd9 - Ashwini Chaudhary
字符串可以像列表一样进行操作,不需要使用 list() - TemporalWolf
最佳答案已在评论中提供:https://dev59.com/F2Ml5IYBdhLWcg3wFTdP - AGN Gazer
还可以查看https://codereview.stackexchange.com/questions/124144/finding-the-fastest-common-prefix-of-2-strings-in-python - AGN Gazer
3个回答

7

没有内置的功能可以完成整个任务,但您可以使用内置的功能来计算公共前缀:

import os
def match(a, b):
    common = os.path.commonprefix([a, b])
    return float(len(common))/len(a)    

太棒了! - AGN Gazer

4

我认为没有内置的方法可以实现这个功能。

但是你可以改进你的实现:

  • 不需要将输入包装在list(...)中。字符串是可索引的。
  • 不需要count变量,i已经具有相同的含义。当你知道结果时,可以立即返回。

像这样,还附加了一些doctests:

def match(a, b):
    """
    >>> match('354575368987943', '354535368987000')
    0.26666666666666666

    >>> match('354575368987943', '354575368987000')
    0.8

    >>> match('354575368987943', '354575368987943')
    1
    """
    for i in range(len(a)):
        if a[i] != b[i]:
            return i / len(a)

    return 1

0

替代方案

(刚才看到下面的答案在我编辑帖子时也想到了同样的事情)

def match(l1, l2):
    # find mismatch
    try:
        stop = next(i for i, (el1, el2) in enumerate(zip(l1, l2)) if el1 != el2)
        return stop/len(l1)
    except StopIteration:
        return 1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接