【Python】內建函式 enumerate

楊奇龍發表於2016-02-23
介紹
在解析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)))
執行結果


注意 Dict 和Str 使用 enmerate 函式的起始值分別從2  1 開始的。


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/22664653/viewspace-1993374/,如需轉載,請註明出處,否則將追究法律責任。

相關文章