Python中enumerate()函式的用法
阿新 • • 發佈:2019-02-01
我們先來看看看幾個簡單的例子:
<span style="font-size:14px;">>>> for i,j in enumerate(('a','b','c')): print i,j 0 a 1 b 2 c >>> for i,j in enumerate([1,2,3]): print i,j 0 1 1 2 2 3 >>> for i,j in enumerate({'a':1,'b':2}): print i,j 0 a 1 b >>> for i,j in enumerate('abc'): print i,j 0 a 1 b 2 c</span>
再看看enumerate的定義:
<span style="font-size:14px;">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</span>
enumerate會將陣列或列表組成一個索引序列。使我們再獲取索引和索引內容的時候更加方便。
在cookbook裡介紹,如果你要計算檔案的行數,可以這樣寫:
count = len(open(thefilepath,'rU').readlines())
前面這種方法簡單,但是可能比較慢,當檔案比較大時甚至不能工作,下面這種迴圈讀取的方法更合適些:
Count = 0
For count,line in enumerate(open(thefilepath,'rU')):
<span style="white-space:pre"> </span>Pass
<span style="white-space:pre"> </span>Count += 1