enumerate(x,y)函數是把元組tuple、字符串str、列表list里面的元素遍歷和索引組合,其用法與range()函數很相似,
下面示例enumerate(x,y)用法以及range(x)相似的用法,但是,enumerate(x,y)函數在遍歷excel等時,可以實現與人視覺了解到的認識更好的理解。
enumerate(x,y)中參數y可以省略,省略時,默認從0開始,
如示例一:
list_words=["this","is","blog","of","white","mouse"]
for idx,word in enumerate(list_words):
print(idx,word)
打印結果:
使用range()函數遍歷實現:
list_words=["this","is","blog","of","white","mouse"]
for i in range(len(list_words)):
print(i,list_words[i])
打印結果:
自定義開始索引號:
示例二:
list_words=["this","is","blog","of","white","mouse"]
for idx,word in enumerate(list_words[1:],2): #也可以寫成for idx,word in enumerate(list_words,start=2):
print(idx,word)
打印結果:
從上面示例中可以看出,enumerate(x,y)中x是需要遍歷的元組tuple、字符串str、列表list,可以和切片組合使用,
y是自定義開始的索引號,根據自己的需要設置開始索引號。