关于python中的enumerate函数的应用
2012-06-04 10:30
429 查看
在python中的enumerate函数是用来遍历列表
用法如下:
lst = [1,2,3]
for index,item in enumerate(lst ):
print '%d : %s' % (index,item)
这里index对应的是列表lst 中的序号,而item则对应列表lst 中的元数。
另外:
返回值为enumerate类:
输出为:
在同时需要index和value值的时候可以使用 enumerate。
用法如下:
lst = [1,2,3]
for index,item in enumerate(lst ):
print '%d : %s' % (index,item)
这里index对应的是列表lst 中的序号,而item则对应列表lst 中的元数。
另外:
python enumerate 用法 | 在for循环中得到计数
参数为可遍历的变量,如 字符串,列表等;返回值为enumerate类:
import string s = string.ascii_lowercase e = enumerate(s) print s print list(e)
输出为:
abcdefghij [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j')]
在同时需要index和value值的时候可以使用 enumerate。
enumerate 实战
line 是个 string 包含 0 和 1,要把1都找出来:#方法一 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'))
相关文章推荐
- 关于python写GUI桌面应用的一些研究结果
- 【脚本语言系列】关于Python网络应用SNMP,你需要知道的事
- 关于python中对象复制和应用的问题
- 关于Python对简单的web框架flask的应用使得不只是本机而是局域网都能访问
- Test@python关于列表及字典的应用_(1)
- 关于Python decorator的应用
- 关于pywin32引起python应用退出时c0000005错误的分析和解决
- 【Python】笔记简记--029:关于读写文件的一个应用项目
- 关于Python的应用发布技术
- Test@python关于列表及字典的应用_(2)
- python关于it审计中的应用
- 关于Python 2to3 的应用.
- 【脚本语言系列】关于Python网络应用Telnet,你需要知道的事
- 关于python中help函数的应用
- python中关于cur.connect()等方法的应用实例
- 关于数据建模(面向ER)和领域模型建模(面向OO)在企业应用中的作用的讨论
- 关于函数指针在单片机上的应用
- 关于Python获取SQLSERVER数据库中文显示乱码问题
- 关于python性能提升的一些方案(上)