Python枚举函数
enumerate()
是Python中的内置函数,可让您在遍历可迭代对象时拥有一个自动计数器。
蟒蛇 enumerate()
功能编号
的 enumerate()
函数采用以下形式:
enumerate(iterable, start=0)
该函数接受两个参数:
iterable
-支持迭代的对象。start
-计数器开始的编号。 此参数是可选的。 默认情况下,计数器从0开始。
enumerate()
返回一个枚举对象,您可以在该对象上调用 __next__()
(要么 next()
在Python 2)方法中获得一个元组,该元组包含一个计数和可迭代的当前值。
这是如何使用创建一个元组列表的示例 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中的大多数内置对象(例如字符串,列表和元组)都是可迭代的。
使用编写更多Pythonic代码 enumerate()
#
Python的 for
循环完全不同于传统的C风格 for
在许多编程语言中都可用的循环。 的 for
Python中的循环等效于其他语言 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()
功能。
如果您有任何疑问或反馈,请随时发表评论。
蟒蛇