Python enumerate() 函数用于访问可迭代对象中的每个项目。此函数接受一个可迭代对象并将其作为 enumerate 对象返回。它还为每个可迭代项添加了一个计数器,以简化迭代过程。
counter 用作 iterable 中每个项目的索引,这有助于遍历。请记住,iterable 是一个对象,它使我们能够通过迭代来访问其项目。
enumerate() 函数是内置函数之一,不需要导入任何模块。
语法
以下是 python enumerate() 函数的语法。
enumerate(iterable, startIndex)
参数
以下是 python enumerate() 函数的参数 -
返回值
python enumerate() 函数返回枚举对象。
enumerate() 函数示例
练习以下示例来理解 Python 中 enumerate() 函数的用法:
示例:使用 enumerate() 函数
以下是 Python enumerate() 函数的示例。在此,我们创建了一个列表,并尝试使用 enumerate() 函数访问其每个元素。
fruitLst = ["Grapes", "Apple", "Banana", "Kiwi"]
newLst = list(enumerate(fruitLst))
print("The newly created list:")
print(newLst)
在执行上述程序时,将生成以下输出 -
The newly created list:
[(0, 'Grapes'), (1, 'Apple'), (2, 'Banana'), (3, 'Kiwi')]
[(0, 'Grapes'), (1, 'Apple'), (2, 'Banana'), (3, 'Kiwi')]
示例:带有 'start' 参数的 enumerate() 函数
如果我们为枚举指定起始索引,则索引号将从指定的 index 值开始。在下面的代码中,我们将 1 指定为起始索引。
fruitLst = ["Grapes", "Apple", "Banana", "Kiwi"]
newLst = list(enumerate(fruitLst, start=1))
print("The newly created list:")
print(newLst)
以下是执行上述程序得到的输出 -
The newly created list:
[(1, 'Grapes'), (2, 'Apple'), (3, 'Banana'), (4, 'Kiwi')]
[(1, 'Grapes'), (2, 'Apple'), (3, 'Banana'), (4, 'Kiwi')]
示例:带有 for 循环的 enumerate() 函数
enumerate() 函数还可以与 for 循环结合使用,以访问列表中的元素,如以下示例所示。
fruitLst = ["Grapes", "Apple", "Banana", "Kiwi"]
print("The newly created list:")
for index, fruit in enumerate(fruitLst):
print(f"Index: {index}, Value: {fruit}")
通过执行上述程序获得以下输出 -
The newly created list:
Index: 0, Value: Grapes
Index: 1, Value: Apple
Index: 2, Value: Banana
Index: 3, Value: Kiwi
Index: 0, Value: Grapes
Index: 1, Value: Apple
Index: 2, Value: Banana
Index: 3, Value: Kiwi
示例:包含元组列表的 enumerate() 函数
在下面的示例中,我们将创建一个元组列表并应用 enumerate() 函数来显示列表的所有元素。
fruits = [(8, "Grapes"), (10, "Apple"), (9, "Banana"), (12, "Kiwi")]
for index, (quantity, fruit) in enumerate(fruits):
print(f"Index: {index}, Quantity: {quantity}, Fruit: {fruit}")
上述程序在执行时显示以下输出 -
Index: 0, Quantity: 8, Fruit: Grapes
Index: 1, Quantity: 10, Fruit: Apple
Index: 2, Quantity: 9, Fruit: Banana
Index: 3, Quantity: 12, Fruit: Kiwi
Index: 1, Quantity: 10, Fruit: Apple
Index: 2, Quantity: 9, Fruit: Banana
Index: 3, Quantity: 12, Fruit: Kiwi