Python中enumerate用法详解

Python中enumerate用法详解

 

enumerate()是python的内置函数、适用于python2.x和python3.x
enumerate在字典上是枚举、列举的意思
enumerate参数为可遍历/可迭代的对象(如列表、字符串)
enumerate多用于在for循环中得到计数,利用它可以同时获得索引和值,即需要index和value值的时候可以使用enumerate
enumerate()返回的是一个enumerate对象

>>> lst = [1, 2, 3, 4, 10, 5]
>>> enumerate(lst)
<enumerate object at 0x00000000032A3990>

enumerate的使用:
例如:已知lst = [1,2,3,4,5,6],要求输出:
0,1
1,2
2,3
3,4
4,5
5,6

复制代码
>>> lst = [1,2,3,4,5,6]
>>> for index,value in enumerate(lst):
  print ('%s,%s' % (index,value))
  
0,1
1,2
2,3
3,4
4,5
5,6
复制代码
复制代码
#指定索引从1开始
>>> lst = [1,2,3,4,5,6]
>>> for index,value in enumerate(lst,1):
print ('%s,%s' % (index,value))

1,1
2,2
3,3
4,4
5,5
6,6

#指定索引从3开始
>>> for index,value in enumerate(lst,3):
print ('%s,%s' % (index,value))

3,1
4,2
5,3
6,4
7,5
8,6
复制代码

补充:
如果要统计文件的行数,可以这样写:
count = len(open(filepath, 'r').readlines())
这种方法简单,但是可能比较慢,当文件比较大时甚至不能工作。

可以利用enumerate():
count = 0
for index, line in enumerate(open(filepath,'r')): 
   count += 1

posted @ 2018-08-01 21:23  我的明天不是梦  阅读(50643)  评论(0编辑  收藏  举报