很多时候,在处理迭代器时,我们还需要保留迭代次数。 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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。