Python枚举

enumerate()是Python中的内置函数,可让您在遍历可迭代对象时拥有一个自动计数器

2 min read
By myfreax
Python枚举

enumerate()是Python中的内置函数,可让您在遍历可迭代对象时拥有一个自动计数器。

Python enumerate()函数

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

enumerate(iterable, start=0)

该函数接受两个参数:

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

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

这里是一个示例,说明如何使用list()创建元组列表以及如何遍历可迭代对象:

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语言代码

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()函数。

如果您有任何问题或反馈,请随时发表评论。

Related Articles