这是我想要的行为:
a: IGADKYFHARGNYDAA
c: KGADKYFHARGNYEAA
2 difference(s).
Run Code Online (Sandbox Code Playgroud)
And*_*den 14
def diff_letters(a,b):
return sum ( a[i] != b[i] for i in range(len(a)) )
Run Code Online (Sandbox Code Playgroud)
|分别为其添加空格键或字符,将结果存储为新字符串.此外,为每个不同的字符增加从零开始的整数值.您可以使用内置zip函数或itertools.izip同时迭代两个字符串,而后者在巨大输入的情况下更高效.如果字符串的大小不同,则迭代只会发生在较短的部分.如果是这种情况,您可以使用不匹配指示字符填充其余部分.
import itertools
def compare(string1, string2, no_match_c=' ', match_c='|'):
if len(string2) < len(string1):
string1, string2 = string2, string1
result = ''
n_diff = 0
for c1, c2 in itertools.izip(string1, string2):
if c1 == c2:
result += match_c
else:
result += no_match_c
n_diff += 1
delta = len(string2) - len(string1)
result += delta * no_match_c
n_diff += delta
return (result, n_diff)
Run Code Online (Sandbox Code Playgroud)
这是一个简单的测试,与上面的例子略有不同.请注意,我使用下划线表示不匹配的字符,以更好地演示如何将结果字符串扩展为较长字符串的大小.
def main():
string1 = 'IGADKYFHARGNYDAA AWOOH'
string2 = 'KGADKYFHARGNYEAA W'
result, n_diff = compare(string1, string2, no_match_c='_')
print "%d difference(s)." % n_diff
print string1
print result
print string2
main()
Run Code Online (Sandbox Code Playgroud)
输出:
niklas@saphire:~/Desktop$ python foo.py
6 difference(s).
IGADKYFHARGNYDAA AWOOH
_||||||||||||_|||_|___
KGADKYFHARGNYEAA W
Run Code Online (Sandbox Code Playgroud)
我想这个例子在这个特定的情况下对你有用而没有太多的复杂性,并且你的python软件版本的互操作性问题(请升级到2.7):
a='IGADKYFHARGNYDAA'
b='KGADKYFHARGNYEAA'
u=zip(a,b)
d=dict(u)
x=[]
for i,j in d.items():
if i==j:
x.append('*')
else:
x.append(j)
print x
Run Code Online (Sandbox Code Playgroud)
输出: ['*', 'E', '*', '*', 'K', '*', '*', '*', '*', '*']
几乎没有tewakings,你可以得到你想要的....告诉我,如果它有帮助:-)
更新
你也可以用这个:
a='IGADKYFHARGNYDAA'
b='KGADKYFHARGNYEAA'
u=zip(a,b)
for i,j in u:
if i==j:
print i,'--',j
else:
print i,' ',j
Run Code Online (Sandbox Code Playgroud)
输出:
I K
G -- G
A -- A
D -- D
K -- K
Y -- Y
F -- F
H -- H
A -- A
R -- R
G -- G
N -- N
Y -- Y
D E
A -- A
A -- A
Run Code Online (Sandbox Code Playgroud)
更新2
您可以像这样修改代码:
y=[]
counter=0
for i,j in u:
if i==j:
print i,'--',j
else:
y.append(j)
print i,' ',j
print '\n', y
print '\n Length = ',len(y)
Run Code Online (Sandbox Code Playgroud)
输出:
I K
G -- G
A -- A
D -- D
K -- K
Y -- Y
F -- F
H -- H
A -- A
R -- R
G -- G
N -- N
Y -- Y
D E
A -- A
A X
['K', 'E', 'X']
Length = 3
Run Code Online (Sandbox Code Playgroud)
Python 具有优秀的difflib,它应该提供所需的功能。
以下是文档中的示例用法:
import difflib # Works for python >= 2.1
>>> s = difflib.SequenceMatcher(lambda x: x == " ",
... "private Thread currentThread;",
... "private volatile Thread currentThread;")
>>> for block in s.get_matching_blocks():
... print "a[%d] and b[%d] match for %d elements" % block
a[0] and b[0] match for 8 elements
a[8] and b[17] match for 21 elements
a[29] and b[38] match for 0 elements
Run Code Online (Sandbox Code Playgroud)