跳至内容
Python 俱乐部
用户工具
登录
站点工具
搜索
工具
显示页面
修订记录
反向链接
最近更改
媒体管理器
网站地图
登录
>
最近更改
媒体管理器
网站地图
您的足迹:
python-basic:built-in
====== python enumerate 用法 ====== ===== python enumerate 用法 | 在for循环中得到计数 ===== 参数为可遍历的变量,如 字符串,列表等; 返回值为enumerate类: <code python> import string s = string.ascii_lowercase e = enumerate(s) print s print list(e) </code> 输出为: <file> abcdefghij [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j')] </file> 在同时需要index和value值的时候可以使用 enumerate。 ===== enumerate 实战 ===== line 是个 string 包含 0 和 1,要把1都找出来: <code python> #方法一 def read_line(line): sample = {} n = len(line) for i in range(n): if line[i]!='0': sample[i] = int(line[i]) return sample #方法二 def xread_line(line): return((idx,int(val)) for idx, val in enumerate(line) if val != '0') print read_line('0001110101') print list(xread_line('0001110101')) </code>
python-basic/built-in.txt
· 最后更改: 2010/06/02 01:18 (外部编辑)
页面工具
显示页面
修订记录
反向链接
回到顶部