ints = [8, 23, 45, 12, 78]
如果像C或者PHP那樣可以加入一個(gè)狀態(tài)變量,這里使用Python最好的選擇就是用內(nèi)建函數(shù)enumerate
for i in range (0,len(list)): print i ,list[i]
但是這種方法有些累贅,使用內(nèi)置enumerrate函數(shù)會(huì)有更加直接,優(yōu)美的做法,先看看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會(huì)將數(shù)組或列表組成一個(gè)索引序列。使我們?cè)佾@取索引和索引內(nèi)容的時(shí)候更加方便如下:
for index,text in enumerate(list)): print index ,text
在cookbook里介紹,如果你要計(jì)算文件的行數(shù),可以這樣寫:
count = len(open(thefilepath,‘rU’).readlines())
前面這種方法簡(jiǎn)單,但是可能比較慢,當(dāng)文件比較大時(shí)甚至不能工作,下面這種循環(huán)讀取的方法更合適些。
Count = -1 For count,line in enumerate(open(thefilepath,‘rU’)): Pass Count += 1
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com