易百教程

82、你对 Python 枚举了解多少?

在使用迭代器时,有时可能会有一个用例来存储迭代次数。 Python 通过提供 enumerate() 内置方法很容易完成这项任务。enumerate() 函数将一个计数器变量附加到一个可迭代对象,并将其作为“枚举”对象返回。
可以直接在“for”循环中使用该对象,或者通过调用 list() 方法将其转换为元组列表。 它具有以下签名:

enumerate(iterable, to_begin=0)
#Arguments:
# iterable: array type object which enables iteration
# to_begin: the base index for the counter is to get started, its default value is 0

示例代码:

# Example - enumerate function 
alist = ["apple","mango", "orange"] 
astr = "banana"\n
# Let's set the enumerate objects 
list_obj = enumerate(alist) 
str_obj = enumerate(astr) 

print("list_obj type:", type(list_obj))
print("str_obj type:", type(str_obj))

print(list(enumerate(alist)) )  
# Move the starting index to two from zero
print(list(enumerate(astr, 2)))

运行结果如下:

list_obj type: <class 'enumerate'>
str_obj type: <class 'enumerate'>
[(0, 'apple'), (1, 'mango'), (2, 'orange')]
[(2, 'b'), (3, 'a'), (4, 'n'), (5, 'a'), (6, 'n'), (7, 'a')]