python獲取字母在字母表對應位置的幾種方法及性能對比較

python獲取字母在字母表對應位置的幾種方法及性能對比較html

某些狀況下要求咱們查出字母在字母表中的順序,A = 1,B = 2 , C = 3, 以此類推,好比這道題目 https://projecteuler.net/problem=42 其中一步解題步驟就是須要把字母換算成字母表中對應的順序。python

獲取字母在字母表對應位置的方法,最容易想到的實現的是:函數

使用str.index 或者str.find方法:oop

In [137]: "ABC".index('B')
Out[137]: 1

In [138]: "ABC".index('B')+1
Out[138]: 2

#或者在前面填充一個字符,這樣index就直接獲得字母序號:
In [139]: "_ABC".index("B")
Out[139]: 2

我還想到把字母表轉成list或者tuple再index,性能或者會有提升? 或者把字母:數字 組成鍵值存到字典中是個好辦法?性能

前兩天我還本身頓悟到了一個方法:測試

In [140]: ord('B')-64
Out[140]: 2

ord 和chr 都是python中的內置函數,ord能夠把ASCII字符轉成對應在ASCII表中的序號,chr則是能夠把序號轉成字符串。.net

大寫字母中在表中是從65開始,減掉64恰好是大寫字母在表中的位置。 小寫字母是從97開始,減於96就是對應的字母表位置。code

哪一種方法可能在性能上更好?我寫了代碼來測試一下:htm

az = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
_az = "_ABCDEFGHIJKLMNOPQRSTUVWXYZ"

azlist = list(az)

azdict = dict(zip(az,range(1,27)))

text = az*1000000 #這個是測試數據

#str.find和str.index的是同樣的。這裏就不必寫了。
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

把上面的代碼複製粘貼到ipython ,而後用魔法函數%timeit測試各個方法的性能。 ipython 是一個python交互解釋器,附帶各類很實用的功能,好比文本主要到的%timeit 功能。 請輸入pip install ipython安裝.blog

如下是我測試的結果數據:

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

從結果中可見到list.index速度最慢,我很意外。另外若是list中數據不少,index會慢得很嚴重。 dict[r]的速度比dict.get(r)的速度快,可是若是是一個不存在的鍵dict[r]會報錯,而dict.get方法不會報錯,容錯性更好。

ord(r)-64的方法速度不錯,使用起來應該也是最方便,不用構造數據。

2016年10月15日 20:31:19 codegay ###擴展閱讀:

ASCII對照表 http://tool.oschina.net/commons?type=4

IPython Tips and Tricks http://blog.endpoint.com/2015/06/ipython-tips-and-tricks.html

相關文章
相關標籤/搜索