Python中enumerate函數用法詳解

來源:互聯網
上載者:User

標籤:...   for   dex   body   padding   containe   series   plain   迴圈   

enumerate函數用於遍曆序列中的元素以及它們的下標,多用於在for迴圈中得到計數,enumerate參數為可遍曆的變數,如 字串,列表等

一般情況下對一個列表或數組既要遍曆索引又要遍曆元素時,會這樣寫:

12 for in range (0,len(list)):   print i ,list[i]

但是這種方法有些累贅,使用內建enumerrate函數會有更加直接,優美的做法,先看看enumerate的定義:

1234567 def enumerate(collection):   ‘Generates an indexed series: (0,coll[0]), (1,coll[1]) ...‘      = 0    it = iter(collection)    while 1   yield (i, it.next())    += 1

 

enumerate會將數組或列表組成一個索引序列。使我們再擷取索引和索引內容的時候更加方便如下:

12 for index,text in enumerate(list)):   print index ,text

 

代碼執行個體1:
12345 = 0seq = [‘one‘‘two‘‘three‘]for element in seq:    print i, seq[i]    += 1

0 one

1 two

2 three

 

代碼執行個體2:
123 seq = [‘one‘‘two‘‘three‘]for i, element in enumerate(seq):    print i, seq[i]

0 one

1 two

2 three

 

代碼執行個體3:
12 for i,j in enumerate(‘abc‘):    print i,j

 

0 a

1 b

2 c

 

Python中enumerate函數用法詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.