找回密码
 注册
搜索
[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
查看: 25068|回复: 9

[原创教程] python获取字母在字母表对应位置的几种方法及性能对比较

[复制链接]
发表于 2016-10-15 20:36:24 | 显示全部楼层 |阅读模式
python获取字母在字母表对应位置的几种方法及性能对比较

某些情况下要求我们查出字母在字母表中的顺序,A = 1,B = 2 , C = 3, 以此类推,比如这道题目 https://projecteuler.net/problem=42
其中一步解题步骤就是需要把字母换算成字母表中对应的顺序。

获取字母在字母表对应位置的方法,最容易想到的实现的是:

使用str.index 或者str.find方法:
  1. In [137]: "ABC".index('B')
  2. Out[137]: 1

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

  5. #或者在前面填充一个字符,这样index就直接得到字母序号:
  6. In [139]: "_ABC".index("B")
  7. Out[139]: 2
复制代码
我还想到把字母表转成list或者tuple再index,性能或者会有提高?
或者把字母:数字 组成键值存到字典中是个好办法?

前两天我还自己顿悟到了一个方法:
  1. In [140]: ord('B')-64
  2. Out[140]: 2
复制代码
ord 和chr 都是python中的内置函数,ord可以把ASCII字符转成对应在ASCII表中的序号,chr则是可以把序号转成字符串。

大写字母中在表中是从65开始,减掉64刚好是大写字母在表中的位置。
小写字母是从97开始,减于96就是对应的字母表位置。

哪种方法可能在性能上更好?我写了代码来测试一下:
  1. az = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2. _az = "_ABCDEFGHIJKLMNOPQRSTUVWXYZ"

  3. azlist = list(az)

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

  5. text = az*1000000 #这个是测试数据

  6. #str.find和str.index的是一样的。这里就没必要写了。
  7. def azindexstr(text):
  8.     for r in text:
  9.         az.index(r)+1
  10.         pass

  11. def _azindexstr(text):
  12.     for r in text:
  13.         _az.index(r)
  14.         pass

  15. def azindexlist(text):
  16.     for r in text:
  17.         azlist.index(r)
  18.         pass

  19. def azindexdict(text):
  20.     for r in text:
  21.         azdict.get(r)
  22.         pass

  23. def azindexdict2(text):
  24.     for r in text:
  25.         azdict[r]
  26.         pass

  27. def azord(text):
  28.     for r in text:
  29.         ord(r)-64
  30.         pass

  31. def azand64(text):
  32.     for r in text:
  33.         ord(r)%64
  34.         pass
复制代码
把上面的代码复制粘贴到ipython ,然后用魔法函数%timeit测试各个方法的性能。
ipython 是一个python交互解释器,附带各种很实用的功能,比如文本主要到的%timeit 功能。
请输入pip install ipython安装.

以下是我测试的结果数据:
  1. In [147]: %timeit azindexstr(text)
  2. 1 loop, best of 3: 9.09 s per loop

  3. In [148]: %timeit _azindexstr(text)
  4. 1 loop, best of 3: 8.1 s per loop

  5. In [149]: %timeit azindexlist(text)
  6. 1 loop, best of 3: 17.1 s per loop

  7. In [150]: %timeit azindexdict(text)
  8. 1 loop, best of 3: 4.54 s per loop

  9. In [151]: %timeit azindexdict2(text)
  10. 1 loop, best of 3: 1.99 s per loop

  11. In [152]: %timeit azord(text)
  12. 1 loop, best of 3: 2.94 s per loop

  13. In [153]: %timeit azand64(text)
  14. 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

评分

参与人数 1技术 +1 收起 理由
happy886rr + 1 不错,学习了

查看全部评分

发表于 2016-10-15 22:04:31 | 显示全部楼层
回复 1# codegay
ord就是快
该题的单词文件为
  1. #ProjectEuler 42:Coded triangle numbers
  2. #2016/10/15 by HAPPY
  3. i=0
  4. for Line in open('p042_words.txt','r'):
  5.         Line=Line.strip(""").split("","")
  6.         for W in Line:
  7.                 S=0
  8.                 for Char in W:
  9.                         S+=ord(Char)-64
  10.                 if( (8*S+1)**0.5==int((8*S+1)**0.5) and int((8*S+1)**0.5)&1==1 ):
  11.                         i+=1
  12. print(i)
复制代码
 楼主| 发表于 2016-10-15 22:12:32 | 显示全部楼层
回复 2# happy886rr


      你这int的写法真奇怪。
发表于 2016-10-15 23:13:42 | 显示全部楼层
回复 3# codegay
那应该如何写,就是要取整,怎么写最好。
发表于 2016-10-15 23:21:20 | 显示全部楼层
回复 4# happy886rr


    (int)var 应该是C里面,python里面int是个函数,所以习惯int(var)
发表于 2016-10-15 23:44:18 | 显示全部楼层
回复 5# 523066680
哦,我把C的写法带到python里了。
  1. #include<stdio.h>
  2. int main()
  3. {
  4.         int i=0,sum,fsize;
  5.         char* Line;
  6.         FILE* fp=fopen("p042_words.txt", "rb");
  7.         if(fp==NULL){return 1;}
  8.         fseek(fp, 0, SEEK_END);
  9.         fsize=ftell(fp)+1;
  10.         Line=(char *)calloc(fsize, sizeof(char));
  11.         fseek(fp, 0, SEEK_SET);
  12.         fgets(Line, fsize, fp);
  13.         fclose(fp);
  14.         for(; *Line!='\0'; Line++){
  15.                 if( 'A'<= *Line && *Line <='Z' ){
  16.                         sum+=*Line-'A'+1;
  17.                 }else{
  18.                         if((int)sqrt(2*sum)*(int)(sqrt(2*sum)+1)-2*sum==0 && sum!=0){i++;}
  19.                         sum=0;
  20.                 }
  21.         }
  22.         printf("%d\n",i);
  23.         return 0;
  24. }
复制代码
发表于 2016-10-16 00:32:13 | 显示全部楼层
批处理版

  1. @echo off&setlocal enabledelayedexpansion
  2. (
  3.         for /l %%j in (1,1,16) do (
  4.                 set/p str[%%j]=
  5.                 set "str[%%j]=!str[%%j]:"=0!"
  6.                 set "str[%%j]=!str[%%j]:,=0!"
  7.         )
  8. )<p042_words.txt
  9. for %%N in (A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z) do (set/a "i+=1,#%%N=i")
  10. for /l %%j in (1,1,16) do (
  11.         set/a "p=%%j*100/16"&echo 正在计算...!p!%%
  12.         for /l %%i in (0,1,1080) do (
  13.                 set "Char=!str[%%j]:~%%i,1!"
  14.                 if not "!Char!"=="0" (
  15.                         set/a "sum+=#!Char!"
  16.                 ) else (
  17.                         for /l %%k in (1,1,20) do (
  18.                                 set/a "k=%%k*(%%k+1)/2"
  19.                                 if !k! equ !sum! (set/a "n+=1")
  20.                         )
  21.                         set/a "sum=0"
  22.                 )
  23.         )
  24. )
  25. set/p=共有!n!个三角数单词
复制代码

评分

参与人数 1技术 +1 收起 理由
codegay + 1 1

查看全部评分

 楼主| 发表于 2016-10-16 08:00:37 | 显示全部楼层
http://www.cnblogs.com/huangjacky/archive/2012/04/19/2457842.html
方法有好几个,效果也各不相同。

类型工厂函数,int(),效果:浮点数取整,如int(3.5)就返回3;数字的字符形式转换成数字,如int("35")就返回35
内置函数的round(),四舍五入,第二个参数是保留小数点后多少位,默认是0,如round(3.5)返回4.0,round(3.5,1)就返回3.5,不能取整。。。囧
math模块的floor(),取小于等于的整数,如floor(3.5)返回3.0,floor(-1.5)返回-2.0,也不能取整。。。再囧
与方法1对应的就是浮点数的类型工厂函数,float(),如float(3)返回3.0,float("3.5")返回3.5
 楼主| 发表于 2016-10-16 08:03:29 | 显示全部楼层
  1. >>> math.ceil(3.5)
  2. 4
复制代码
 楼主| 发表于 2016-10-16 08:18:27 | 显示全部楼层
发现//这个方法是个坑。碰上浮点数的时候不是返回整形
  1. >>> 3.5//1
  2. 3.0
  3. >>> 3.5//1.0
  4. 3.0
  5. >>> 3.5//10
  6. 0.0
  7. >>> 3.5//2
  8. 1.0
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|批处理之家 ( 渝ICP备10000708号 )

GMT+8, 2026-3-17 00:49 , Processed in 0.018475 second(s), 8 queries , File On.

Powered by Discuz! X3.5

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表