很多时候,在处理迭代器时,我们还需要保留迭代次数。Python通过为该任务提供内置函数enumerate()减轻了程序员的任务。
Enumerate()方法向可迭代对象添加一个计数器,并以枚举对象的形式返回它。然后可以将此枚举对象直接用于for循环,或使用list()方法将其转换为元组列表。

句法:

枚举(可迭代,开始= 0)

参数:
可迭代:任何对象支持迭代
开始:索引值从该计数器是
              要启动,默认为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: < type 'enumerate' >
[(0, 'eat'), (1, 'sleep'), (2, 'repeat')]
[(2, 'g'), (3, 'e'), (4, 'e'), (5, 'k')]

 


在循环中使用枚举对象
# 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

 

 

分类:

技术点:

相关文章: