这篇文章主要介绍了python中enumerate的用法,对Python初学者而言是非常重要的概念
来源:互联网 发布:第一版主小说网新域名 编辑:程序博客网 时间:2024/05/16 13:58
在python中enumerate的用法多用于在for循环中得到计数,本文即以实例形式向大家展现python中enumerate的用法。具体如下:
enumerate参数为可遍历的变量,如 字符串,列表等; 返回值为enumerate类。
示例代码如下www.97sexsex.com所示:
view sourceprint?1 import string
2 s = string.ascii_lowercase
3 e = enumerate(s)
4 print s
5 print list(e)
输出为:
view sourceprint?1 abcdefghij
2 [(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都找出来:
方法一:
view sourceprint?1 def read_line(line):
2 sample = {}
3 n = len(line)
4 for i in range(n):
5 if line[i]!='0':
6 sample[i] = int(line[i])
7 return sample
方法二www.555ni.com:
view sourceprint?1 def xread_line(line):
2 return((idx,int(val)) for idx, val in enumerate(line) if val != '0')
3
4 print read_line('0001110101')
5 print list(xread_line('0001110101'))
相信本文示例对大家加深对Python中enumerate的用法能够起到一定的帮助作用。
enumerate参数为可遍历的变量,如 字符串,列表等; 返回值为enumerate类。
示例代码如下www.97sexsex.com所示:
view sourceprint?1 import string
2 s = string.ascii_lowercase
3 e = enumerate(s)
4 print s
5 print list(e)
输出为:
view sourceprint?1 abcdefghij
2 [(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都找出来:
方法一:
view sourceprint?1 def read_line(line):
2 sample = {}
3 n = len(line)
4 for i in range(n):
5 if line[i]!='0':
6 sample[i] = int(line[i])
7 return sample
方法二www.555ni.com:
view sourceprint?1 def xread_line(line):
2 return((idx,int(val)) for idx, val in enumerate(line) if val != '0')
3
4 print read_line('0001110101')
5 print list(xread_line('0001110101'))
相信本文示例对大家加深对Python中enumerate的用法能够起到一定的帮助作用。
0 0
- 这篇文章主要介绍了python中enumerate的用法,对Python初学者而言是非常重要的概念
- Python中enumerate的用法
- Python中enumerate的用法
- 这篇文章主要介绍了Python使用函数默认值实现函数静态变量的方法,是很实用的功能
- python enumerate 的用法
- 这篇文章主要介绍了Python os模块介绍,需要的朋友可以参考下
- Python中enumerate()函数的用法
- python中enumerate()函数的用法
- Python中的enumerate的用法
- Python的enumerate用法总结
- python中enumerate用法
- Python中enumerate用法
- Python学习笔记:python中enumerate函数的用法
- Python 中enumerate的使用
- python 函数-enumerate的用法
- python中的enumerate函数的用法
- python中enumerate函数用法
- python的enumerate()函数
- 柯震东被关6天终见父母 40分钟三口泪奔
- ubuntu shadowsocks(python) 自动启动
- SDUT 2929-人活着系列之芳姐和芳姐的猪(最短路Floyd)
- Android ValueAnimation
- 注解 @Resource 【转】
- 这篇文章主要介绍了python中enumerate的用法,对Python初学者而言是非常重要的概念
- iOS App启动动画
- 集合中按照类型分类
- 柯震东被关6天终见父母 40分钟三口泪奔
- 庆功会
- cocos2d-x一些概念
- poj 1936 All in All
- Select查询数据放一个内表,然后在下一条select语句用where语句in 该内表
- 函数调用与约定