本文为你讲解Python枚举:Python enumerate()函数及使用enumerate()编写更多Pythonic代码,以下内容适用于Linux平台中。enumerate()是Python中的内置函数,可让你在遍历可迭代对象时拥有一个自动计数器。
Python enumerate()函数
enumerate()函数采用以下形式:
enumerate(iterable, start=0)
该函数接受两个参数:
1]、iterable-支持迭代的对象。
2]、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()编写更多Pythonic代码
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()函数的基本方法。
相关主题