als 组成 utf-8 解析 enumerate strong 索引 ret
- #!usr/bin/env python
- #coding:utf-8
- ‘‘‘
- enumerate()说明:
- 1、enumerate()是Python的内置函数;
- 2、enumerate字面上是枚举、列举的意思;
- 3、对于一个可迭代、可遍历的对象(列表、元组、字符串),enumerate将其组成一个索引序列,利用
- 它可以同时获得索引和值;
- 4、enumerate多用于for循环中得到计数;
- 5、注意:enumerate()返回的是enumerate对象;
- ‘‘‘
- ‘‘‘
- 需求:给定一串数字01098040234,将非0的数字所处的位置及值进行打印输出;
- ‘‘‘
- str1 = ‘01098040234‘
- def findNotZero(str):
- return ((index,value) for index,value in enumerate(str) if value!=‘0‘)
- print(findNotZero(str1))
5、注意:enumerate()返回的是enumerate对象--运行结果如下所示
- <generator object findNotZero.<locals>.<genexpr> at 0x00000223A8416A98>
- [Finished in 0.1s]
- #!usr/bin/env python
- #coding:utf-8
- ‘‘‘
- enumerate()说明:
- 1、enumerate()是Python的内置函数;
- 2、enumerate字面上是枚举、列举的意思;
- 3、对于一个可迭代、可遍历的对象(列表、元组、字符串),enumerate将其组成一个索引序列,利用
- 它可以同时获得索引和值;
- 4、enumerate多用于for循环中得到计数;
- 5、注意:enumerate()返回的是enumerate对象;
- ‘‘‘
- ‘‘‘
- 需求:给定一串数字01098040234,将非0的数字所处的位置及值进行打印输出;
- ‘‘‘
- str1 = ‘01098040234‘
- def findNotZero(str):
- return ((index,value) for index,value in enumerate(str) if value!=‘0‘)
- print(list(findNotZero(str1)))
运行结果:
- [(1, ‘1‘), (3, ‘9‘), (4, ‘8‘), (6, ‘4‘), (8, ‘2‘), (9, ‘3‘), (10, ‘4‘)]
- [Finished in 0.1s]
注意点:
1、enumerate()指定起始下标enumerate(str,1)
2、列表解析式:[expr for iter_var in iterable if cond_expr]
enumerate()的优势:
需求:给你一个列表[‘我’,‘是’,‘寒’,‘岳’];现在想要同时将每个列表元素的索引位置及值同时打印输出;
最直接的做法就是:
- for i in range(len(list1)):
- print (i,list1[i])
运行结果:
- 0 我
- 1 是
- 2 寒
- 3 岳
- [Finished in 0.2s]
上述方法有些累赘,利用enumerate()会更加直接和优美:
- list1 = [‘我‘, ‘是‘, ‘寒‘, ‘岳‘]
- for index,
- value in enumerate(list1) : print(index, value)
运行结果:
- 0 我
- 1 是
- 2 寒
- 3 岳
- [Finished in 0.1s]
enumerate() -- Python
来源: http://www.bubuko.com/infodetail-2282801.html