python函数3:enumerate

概念:
1.enumerate()是python的内置函数
2.enumerate在字典上是枚举、列举的意思
3.对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值
4.enumerate多用于在for循环中得到计数

如果对一个列表,既要遍历索引又要遍历元素时:

list=['This','is','an','example']
for index, item in enumerate(list):
	print(index,item)

执行结果:

0 This
1 is
2 an
3 example

enumerate()还可以指定索引的起始值:

list=['This','is','an','example']
for index, item in enumerate(list,1):
	print(index,item)

执行结果:

1 This
2 is
3 an
4 example

还有一个普遍的应用在于统计文件行数,特别是大文件
示例代码:

count = 0
for index, line in enumerate(open(file_path,'r')): 
count += 1

你可能感兴趣的:(python函数)