码迷,mamicode.com
首页 > 编程语言 > 详细

The Hamming distance in python

时间:2017-01-12 12:48:22      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:diff   返回   距离   元素   next   man   span   blog   对象   

 需要用到一个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

标签:diff   返回   距离   元素   next   man   span   blog   对象   

原文地址:http://www.cnblogs.com/nklzj/p/6275782.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!