且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

【Python】内置函数 enumerate

更新时间:2022-06-15 12:04:39

介绍
在解析mysqlbinlog dump出来的binlog的时候学习了一个函数 --enumerate。官方的定义如下:
  1. def enumerate(collection,N=0):
  2.     'Generates an indexed series: (0,coll[0]), (1,coll[1]) ...'
  3.     i = N
  4.     it = iter(collection)
  5.     while 1:
  6.         yield (i, it.next())
  7.         i += 1
N 是索引起始值 比如 enumerate(list,2) 索引是从2 开始。
通常我们需要遍历序列如 字符串,字典,列表,也要遍历其索引时,我们会使用for 循环来解决 
  1. for i in range (0,len(list)):
  2.        print i ,list[i]
使用内置enumerrate函数会有更加直接,优美的做法
  1. for idx,name in enumerate(list)):
  2.     print idx,name
如何使用该函数
  1. #coding=utf-8
    List = ['a', 'b', 'c']
    print (list(enumerate(List)))
    Tuple = ('youzan', 'SAAS', 'work','Mac')
    print(list(enumerate(Tuple)))
    Dict = {"city":"HANGZHOU", 'company':"youzan", 'dba':'yangyi'}
    print(list(enumerate(Dict, 2)))
    Str = 'YOUZAN!'
    print(list(enumerate(Str, 1)))
运行结果
【Python】内置函数 enumerate

注意 Dict 和Str 使用 enmerate 函数的起始值分别从2  1 开始的。