enumerate函数用于遍历序列中的元素以及它们的下标。
enumerate函数说明:
enumerate()是python的内置函数
enumerate在字典上是枚举、列举的意思
函数原型:enumerate(sequence, [start=0])
功能:将可循环序列sequence以start开始分别列出序列数据和数据下标
即对一个可遍历的数据对象(如列表、元组或字符串),enumerate会将该数据对象组合为一个索引序列,同时列出数据和数据下标。
举例说明:
存在一个sequence,对其使用enumerate将会得到如下结果:
start sequence[0]
start+1 sequence[1]
start+2 sequence[2]......
适用版本:
Python2.3+
Python2.x
注意:在python2.6以后新增了start参数
英文解释:
Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence。
代码实例:
enumerate参数为可遍历的变量,如 字符串,列表等; 返回值为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。
该实例中,line 是个 string 包含 0 和 1,要把1都找出来:
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'))
如果对一个列表,既要遍历索引又要遍历元素时,首先可以这样写:
list1 = ["这", "是", "一个", "测试"]
for i in range (len(list1)):
print i ,list1[i]
上述方法有些累赘,利用enumerate()会更加直接和优美:
list1 = ["这", "是", "一个", "测试"]
for index, item in enumerate(list1):
print index, item
>>>
0 这
1 是
2 一个
3 测试
enumerate还可以接收第二个参数,用于指定索引起始值,如:
list1 = ["这", "是", "一个", "测试"]
for index, item in enumerate(list1, 1):
print index, item
>>>
1 这
2 是
3 一个
4 测试
补充
如果要统计文件的行数,可以这样写:
count = len(open(filepath, 'r').readlines())
这种方法简单,但是可能比较慢,当文件比较大时甚至不能工作。
可以利用enumerate():
count = 0
for index, line in enumerate(open(filepath,'r')):
count += 1
来源:http://www.pythontab.com/html/2017/hanshu_0517/1141.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
vue后台管理添加多语言功能的实现示例
jupyter notebook参数化运行python方式
![](https://img.aspxhome.com/file/2023/1/70111_0s.jpg)
使用Python脚本来获取Cisco设备信息的示例
Python爬虫之网页图片抓取的方法
![](https://img.aspxhome.com/file/2023/3/78523_0s.png)
Python +Selenium解决图片验证码登录或注册问题(推荐)
MySQL存储引擎InnoDB与Myisam的区别分析
JS实现点击表头表格自动排序(含数字、字符串、日期)
![](https://img.aspxhome.com/file/2023/4/132714_0s.png)
JS中定位 position 的使用实例代码
Python matplotlib学习笔记之坐标轴范围
![](https://img.aspxhome.com/file/2023/8/88038_0s.jpg)
python算法加密 pyarmor与docker
![](https://img.aspxhome.com/file/2023/5/131385_0s.png)
PHP写的求多项式导数的函数代码
Python编程实现线性回归和批量梯度下降法代码实例
![](https://img.aspxhome.com/file/2023/5/120915_0s.png)
详解python进行mp3格式判断
浅谈django中的认证与登录
python时间日期函数与利用pandas进行时间序列处理详解
Python使用三种方法实现PCA算法
![](https://img.aspxhome.com/file/2023/6/112026_0s.png)
Oracle9i 动态SGA,PGA特性探索
利用Python改正excel表格数据
![](https://img.aspxhome.com/file/2023/1/133561_0s.png)
Pycharm不同版本镜像源添加方法
![](https://img.aspxhome.com/file/2023/2/77562_0s.jpg)
Python中Requests-get方法的使用
![](https://img.aspxhome.com/file/2023/0/133810_0s.png)