Python enumerate() 函数



Python enumerate() 函数用于访问可迭代对象中的每个项目。此函数接受一个可迭代对象并将其作为枚举对象返回。它还为每个可迭代项添加一个计数器,以简化迭代过程。

计数器充当可迭代项的每个项目的索引,有助于遍历。请记住,可迭代对象是一个允许我们通过迭代访问其项目的对象。

enumerate() 函数是 内置函数 之一,不需要导入任何模块。

语法

以下是 python enumerate() 函数的语法。

enumerate(iterable, startIndex)

参数

以下是 python enumerate() 函数的参数:

  • iterable - 此参数表示一个可迭代对象,例如 列表元组字典集合

  • startIndex - 它指定可迭代对象的起始索引。这是一个可选参数,其默认值为 0。

返回值

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')]

示例:带有 'start' 参数的 enumerate() 函数

如果我们为枚举指定起始索引,则索引号将从指定的索引值开始。在下面的代码中,我们将 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')]

示例:带有 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

示例:带有元组列表的 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
python_built_in_functions.htm
广告
© . All rights reserved.