來(lái)源:黑暗圣堂武士
python獲取字母在字母表對(duì)應(yīng)位置的幾種方法及性能對(duì)比較
某些情況下要求我們查出字母在字母表中的順序则涯,A = 1,B = 2 , C = 3见秽, 以此類(lèi)推,比如這道題目 https://projecteuler.net/problem=42 其中一步解題步驟就是需要把字母換算成字母表中對(duì)應(yīng)的順序浪南。
獲取字母在字母表對(duì)應(yīng)位置的方法,最容易想到的實(shí)現(xiàn)的是:
使用str.index 或者str.find方法:
In [137]: "ABC".index('B')
Out[137]: 1
In [138]: "ABC".index('B')+1
Out[138]: 2
#或者在前面填充一個(gè)字符,這樣index就直接得到字母序號(hào):
In [139]: "_ABC".index("B")
Out[139]: 2
我還想到把字母表轉(zhuǎn)成list或者tuple再index尾膊,性能或者會(huì)有提高媳危? 或者把字母:數(shù)字 組成鍵值存到字典中是個(gè)好辦法?
前兩天我還自己頓悟到了一個(gè)方法:
In [140]: ord('B')-64
Out[140]: 2
ord 和chr 都是python中的內(nèi)置函數(shù),ord可以把ASCII字符轉(zhuǎn)成對(duì)應(yīng)在ASCII表中的序號(hào),chr則是可以把序號(hào)轉(zhuǎn)成字符串冈敛。
大寫(xiě)字母中在表中是從65開(kāi)始待笑,減掉64剛好是大寫(xiě)字母在表中的位置。 小寫(xiě)字母是從97開(kāi)始抓谴,減于96就是對(duì)應(yīng)的字母表位置暮蹂。
哪種方法可能在性能上更好?我寫(xiě)了代碼來(lái)測(cè)試一下:
az = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
_az = "_ABCDEFGHIJKLMNOPQRSTUVWXYZ"
azlist = list(az)
azdict = dict(zip(az,range(1,27)))
text = az*1000000 #這個(gè)是測(cè)試數(shù)據(jù)
#str.find和str.index的是一樣的癌压。這里就沒(méi)必要寫(xiě)了仰泻。
def azindexstr(text):
for r in text:
az.index(r)+1
pass
def _azindexstr(text):
for r in text:
_az.index(r)
pass
def azindexlist(text):
for r in text:
azlist.index(r)
pass
def azindexdict(text):
for r in text:
azdict.get(r)
pass
def azindexdict2(text):
for r in text:
azdict[r]
pass
def azord(text):
for r in text:
ord(r)-64
pass
def azand64(text):
for r in text:
ord(r)%64
pass
把上面的代碼復(fù)制粘貼到ipython ,然后用魔法函數(shù)%timeit測(cè)試各個(gè)方法的性能滩届。 ipython 是一個(gè)python交互解釋器集侯,附帶各種很實(shí)用的功能,比如文本主要到的%timeit 功能帜消。 請(qǐng)輸入pip install ipython安裝.
以下是我測(cè)試的結(jié)果數(shù)據(jù):
In [147]: %timeit azindexstr(text)
1 loop, best of 3: 9.09 s per loop
In [148]: %timeit _azindexstr(text)
1 loop, best of 3: 8.1 s per loop
In [149]: %timeit azindexlist(text)
1 loop, best of 3: 17.1 s per loop
In [150]: %timeit azindexdict(text)
1 loop, best of 3: 4.54 s per loop
In [151]: %timeit azindexdict2(text)
1 loop, best of 3: 1.99 s per loop
In [152]: %timeit azord(text)
1 loop, best of 3: 2.94 s per loop
In [153]: %timeit azand64(text)
1 loop, best of 3: 4.56 s per loop
從結(jié)果中可見(jiàn)到list.index速度最慢棠枉,我很意外。另外如果list中數(shù)據(jù)很多泡挺,index會(huì)慢得很?chē)?yán)重辈讶。 dict[r]的速度比dict.get(r)的速度快,但是如果是一個(gè)不存在的鍵dict[r]會(huì)報(bào)錯(cuò),而dict.get方法不會(huì)報(bào)錯(cuò)娄猫,容錯(cuò)性更好贱除。
ord(r)-64的方法速度不錯(cuò)生闲,使用起來(lái)應(yīng)該也是最方便,不用構(gòu)造數(shù)據(jù)勘伺。
2016年10月15日 20:31:19 codegay
擴(kuò)展閱讀:
ASCII對(duì)照表 http://tool.oschina.net/commons?type=4
IPython Tips and Tricks http://blog.endpoint.com/2015/06/ipython-tips-and-tricks.html