python中enumerate函數用法執行個體分析

來源:互聯網
上載者:User
本文執行個體講述了python中enumerate函數用法。分享給大家供大家參考。具體分析如下:

今日發現一個新函數 enumerate 。一般情況下對一個列表或數組既要遍曆索引又要遍曆元素時,會這樣寫:

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

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

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

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

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

在cookbook裡介紹,如果你要計算檔案的行數,可以這樣寫:

count = len(open(thefilepath,'rU').readlines())

前面這種方法簡單,但是可能比較慢,當檔案比較大時甚至不能工作,下面這種迴圈讀取的方法更合適些。

Count = -1 For count,line in enumerate(open(thefilepath,'rU')):   PassCount += 1

希望本文所述對大家的python程式設計有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.