Python 枚举的用法

enumerate() 是 Python 中的内置函数,可让您方便的遍历可迭代对象。

Python  enumerate() 函数

enumerate() 函数采用以下形式:

enumerate(iterable, start=0)

该函数接受两个参数:

  • iterable - 支持迭代的对象。
  • start - 计数器开始的编号。此参数是可选的。默认情况下,计数器从0开始。

enumerate() 返回一个枚举对象,您可以在该对象上调用 __next__()(或在 Python 2 中的 next())方法以获取一个元组,该元组包含一个计数和可迭代的当前值。

下面的示例演示了如何遍历可迭代对象:

directions = ["north", "east", "south", "west"] 
list(enumerate(directions))

for index, value in enumerate(directions): 
    print("{}: {}".format(index, value))
[(0, 'north'), (1, 'east'), (2, 'south'), (3, 'west')]

0: north
1: east
2: south
3: west

如果从零开始的索引不适合您,请为枚举选择另一个起始索引:

directions = ["north", "east", "south", "west"] 
list(enumerate(directions, 1))
[(1, 'north'), (2, 'east'), (3, 'south'), (4, 'west')]

enumerate() 函数可用于任何可迭代对象。可迭代的是可以迭代的容器。用简单的话来说,它意味着您可以在 for 循环中使用一个对象。 Python 中的大多数内置对象(例如字符串,列表和元组)都是可迭代的。

编写更多 enumerate() 代码 

Python 的 for 循环与许多编程语言中可用的传统 C 样式 for 循环完全不同。Python 中的 for 循环等效于其他语言的 foreach 循环。

新 Python 开发人员在处理可迭代对象时用于获取相应索引的常用技术是使用 range(len(...)) 模式或显示的增加计数器:

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
for i in range(len(planets)):
    print("Planet {}: {}".format(i, planets[i]))
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
i = 0
for planet in planets:
    print("Planet {}: {}".format(i, planet))
    i += 1

我么可以使用 enumerate() 重写以上循环:

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
for index, value in enumerate(planets): 
    print("Planet {}: {}".format(index, value))

所有方法将产生相同的输出:

Planet 0: Mercury
Planet 1: Venus
Planet 2: Earth
Planet 3: Mars
Planet 4: Jupiter
Planet 5: Saturn
Planet 6: Uranus
Planet 7: Neptune

结论

在本文中,我们向您展示了如何使用 Python 的 enumerate() 函数。