python_enumerate用法

enumerate()是 Python 内置函数,列举、枚举,对于一个可迭代的(iterable)对象(如列表、字符串),enumerate 将其组成一个索引序列,利用它可以同时获得索引和值。

enumerate(sequence, [start=0]),  start是起始下标值

普通 for 循环与 enumerate:

1、

>>> list1 = ['hello','my','little','star']

>>> print(list1)

['hello', 'my', 'little', 'star']

>>> for i in range(len(list1)):

...   print(i,list1[i])

... 

0 hello

1 my

2 little

3 star

2、

>>> for index,item in enumerate(list1,1):

...   print(index,item)

... 

1 hello

2 my

3 little

4 star

附:使用 enumerate 统计文件行数

1、count = len(open(filepath,'r').readlines()) 较慢

2、count = 0

    for index,line in enumerate(open(filepath,'r')):

         count += 1

原文地址:https://www.cnblogs.com/yml6/p/7714398.html