python获取字母在字母表对应位置的几种方法及性能对比较
某些情况下要求我们查出字母在字母表中的顺序,A = 1,B = 2 , C = 3, 以此类推,比如这道题目 https://projecteuler.net/problem=42
其中一步解题步骤就是需要把字母换算成字母表中对应的顺序。
获取字母在字母表对应位置的方法,最容易想到的实现的是:
使用str.index 或者str.find方法: | In [137]: "ABC".index('B') | | Out[137]: 1 | | | | In [138]: "ABC".index('B')+1 | | Out[138]: 2 | | | | | | In [139]: "_ABC".index("B") | | Out[139]: 2COPY |
我还想到把字母表转成list或者tuple再index,性能或者会有提高?
或者把字母:数字 组成键值存到字典中是个好办法?
前两天我还自己顿悟到了一个方法: | In [140]: ord('B')-64 | | Out[140]: 2COPY |
ord 和chr 都是python中的内置函数,ord可以把ASCII字符转成对应在ASCII表中的序号,chr则是可以把序号转成字符串。
大写字母中在表中是从65开始,减掉64刚好是大写字母在表中的位置。
小写字母是从97开始,减于96就是对应的字母表位置。
哪种方法可能在性能上更好?我写了代码来测试一下: | az = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" | | _az = "_ABCDEFGHIJKLMNOPQRSTUVWXYZ" | | | | azlist = list(az) | | | | azdict = dict(zip(az,range(1,27))) | | | | text = az*1000000 | | | | | | 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 | | passCOPY |
把上面的代码复制粘贴到ipython ,然后用魔法函数%timeit测试各个方法的性能。
ipython 是一个python交互解释器,附带各种很实用的功能,比如文本主要到的%timeit 功能。
请输入pip install ipython安装.
以下是我测试的结果数据: | 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 loopCOPY |
从结果中可见到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 |