首页 > 代码库 > The Hamming distance in python

The Hamming distance in python

 需要用到一个zip函数。首先看一下zip函数可以用来干什么:

 1 >>> name=(jack,beginman,sony,pcky)
 2 >>> age=(2001,2003,2005,2000)
 3 >>> for a,n in zip(name,age):
 4     print a,n
 5 
 6 输出:
 7 jack 2001
 8 beginman 2003
 9 sony 2005
10 pcky 2000

再看:

1 x = [1, 2, 3]
2 y = [4, 5, 6, 7]
3 xy = zip(x, y)
4 print xy

运行的结果是:

[(1, 4), (2, 5), (3, 6)]

再看:

1 x = [1, 2, 3]
2 
3 y = [4, 5, 6]
4 
5 z = [7, 8, 9]
6 
7 xyz = zip(x, y, z)
8 
9 print xyz    

运行的结果是:

[(1, 4, 7), (2, 5, 8), (3, 6, 9)]


zip函数接受一系列可迭代对象作为参数,将对象中对应的元素打包成一个个tuple,然后返回由这些tuples做成的list,这是在python2中,在python3中如下:

1 x = [1, 2, 3]
2 
3 y = [4, 5, 6]
4 
5 z = [7, 8, 9]
6 
7 xyz = zip(x, y, z)
8 print (xyz)
9  <zip object at 0x0325AE40>

即在python3种不是一个list,而是一个迭代器:

 

1 >>> next(xyz)
2 (1, 4, 7)
3 >>> next(xyz)
4 (2, 5, 8)
5 >>> next(xyz)
6 (3, 6, 9)
7 >>> next(xyz)

 

利用zip求汉明距离:

>>>str1 = AGCTAGCT
>>>str2 = TTCTAGCT
>>> diffs = 0
>>> for ch1,ch2 in zip(str1,str2):
            if ch1 != ch2:
            diffs += 1
>>>print (diffs)

结果会是2。很方便

 

The Hamming distance in python