Python中的枚举()
通常,在处理迭代器时,我们还需要保持迭代计数。 Python通过为该任务提供内置函数enumerate() 来简化程序员的任务。
Enumerate() 方法向可迭代对象添加一个计数器,并以枚举对象的形式返回它。然后这个枚举对象可以直接用于循环或使用 list() 方法转换为元组列表。
句法:
enumerate(iterable, start=0)
Parameters:
Iterable: any object that supports iteration
Start: the index value from which the counter is
to be started, by default it is 0
Python3
# python
# 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)))
Python3
# 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)
# changing index and printing separately
for count, ele in enumerate(l1, 100):
print (count, ele)
# getting desired output from tuple
for count, ele in enumerate(l1):
print(count)
print(ele)
输出:
Return type:
[(0, 'eat'), (1, 'sleep'), (2, 'repeat')]
[(2, 'g'), (3, 'e'), (4, 'e'), (5, 'k')]
在循环中使用枚举对象:
Python3
# 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)
# changing index and printing separately
for count, ele in enumerate(l1, 100):
print (count, ele)
# getting desired output from tuple
for count, ele in enumerate(l1):
print(count)
print(ele)
输出:
(0, 'eat')
(1, 'sleep')
(2, 'repeat')
100 eat
101 sleep
102 repeat
0
eat
1
sleep
2
repeat