簡體   English   中英

Python比較兩個字符串

[英]Python comparing two strings

有沒有一個函數可以比較兩個(相同長度)字符串之間有多少個字符不同? 我的意思是只換人。 例如,AAA與AAT的區別是1個字符。

這將起作用:

>>> str1 = "AAA"
>>> str2 = "AAT"
>>> sum(1 for x,y in enumerate(str1) if str2[x] != y)
1
>>> str1 = "AAABBBCCC"
>>> str2 = "ABCABCABC"
>>> sum(1 for x,y in enumerate(str1) if str2[x] != y)
6
>>>

上面的解決方案使用sumenumerategenerator表達式


因為True可以求值為1 ,所以您甚至可以執行以下操作:

>>> str1 = "AAA"
>>> str2 = "AAT"
>>> sum(str2[x] != y for x,y in enumerate(str1))
1
>>>

但是我個人更喜歡第一個解決方案,因為它更清晰。

這是zip功能的一個很好的用例!

def count_substitutions(s1, s2):
    return sum(x != y for (x, y) in zip(s1, s2))

用法:

>>> count_substitutions('AAA', 'AAT')
1

從文檔:

zip(...)
    zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

    Return a list of tuples, where each tuple contains the i-th element
    from each of the argument sequences.  The returned list is truncated
    in length to the length of the shortest argument sequence.

根據p說的內容,我建議您使用水母包裝。 它具有幾種您想要的距離測量方法。 文檔中的示例:

IN [1]: jellyfish.damerau_levenshtein_distance('jellyfish', 'jellyfihs')
OUT[1]: 1

或使用您的示例:

IN [2]: jellyfish.damerau_levenshtein_distance('AAA','AAT')
OUT[2]: 1

這將適用於許多不同的字符串長度,並且應該能夠處理您扔給它的大部分內容。

與simon的答案類似,但您不必為了在結果元組上調用函數而壓縮所有內容,因為無論如何,這就是map功能(以及Python 2中的itertools.imap )。 並且operator有一個方便的!=功能。 因此:

sum(map(operator.ne, s1, s2))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM