python 函數enumerate(x,y)的用法


  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是自定義開始的索引號,根據自己的需要設置開始索引號。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM