python的for如何獲得當前循環次數?

python的for如何獲得當前循環次數?

摘自:http://markmail.org/message/ryfven2i75kgsrsm


enumerate是python 2.3中新增的內置函數,它的英文說明爲:

enumerate( iterable)

Return an enumerate object. iterable must be a sequence, an iterator,or some other object which supports iteration. The next() method ofthe iterator returned by enumerate() returns a tuple containing acount (from zero) and the corresponding value obtained from iteratingover iterable. enumerate() is useful for obtaining an indexed series:(0, seq[0]), (1, seq[1]), (2, seq[2]), .... New in version 2.3.它特別適合用於一個for循環時,當我們同時需要計數和元素時可以使用這個函數。舉個簡單的例子,有一個字符串數組,需要一行一行打印出來,同時每行前面加上計數,從1開始。

s = ['abc', 'This is a test', 'Hello, Python']

for i, line in enumerate(s):

print i+1, line

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章