很多時候,在處理迭代器時,我們還需要保留迭代次數。 Python通過提供內置函數enumerate()來簡化程序員的任務。
Enumerate()方法向可迭代對象添加一個計數器,並以枚舉對象的形式返回它。然後,可以直接在for循環中使用此枚舉對象,或使用list()方法將其轉換為元組列表。
用法:
enumerate(iterable, start=0) 參數: Iterable:any object that supports iteration Start:the index value from which the counter is to be started, by default it is 0
# Python program to illustrate
# enumerate function
l1 = ["eat","sleep","repeat"]
s1 = "geek"
# creating enumerate objects
obj1 = enumerate(l1)
obj2 = enumerate(s1)
print "Return type:",type(obj1)
print list(enumerate(l1))
# changing start index to 2 from 0
print list(enumerate(s1,2))
輸出:
Return type: [(0, 'eat'), (1, 'sleep'), (2, 'repeat')] [(2, 'g'), (3, 'e'), (4, 'e'), (5, 'k')]
Using Enumerate object in loops
# Python program to illustrate
# enumerate function in loops
l1 = ["eat","sleep","repeat"]
# printing the tuples in object directly
for ele in enumerate(l1):
print ele
print
# changing index and printing separately
for count,ele in enumerate(l1,100):
print count,ele
輸出:
(0, 'eat') (1, 'sleep') (2, 'repeat') 100 eat 101 sleep 102 repeat
相關用法
注:本文由純淨天空篩選整理自 Enumerate() in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。