如何在Python编程语言中枚举?

Python为程序员提供了易于使用的函数和机制。在处理集合或列表类型时,我们通常需要一些方法来枚举它们。 enumerate() 函数用于从给定的列表或集合创建iterable或enumerable类型。在这个操作之后,我们可以使用创建的对象来迭代 for while 结构。

null

列举

我们将从一个简单的枚举示例开始。我们将提供一份名为 fruits enumerate() 函数,该函数将用元组格式的索引编号列表更改列表。

fruits=['apple','lemon','cherry','orange'] list(enumerate(fruits))                    #This will print#[(0, 'apple'), (1, 'lemon'), (2, 'cherry'), (3, 'orange')]
Simply Enumerate
简单列举

用计数器枚举

我们可以通过指定 start 参数如下。我们可以在下面的例子中看到 start 索引将为 1 不违约 .

fruits=['apple','lemon','cherry','orange'] list(enumerate(fruits,start=1))  #This will print          # [(1, 'apple'), (2, 'lemon'), (3, 'cherry'), (4, 'orange')]
Enumerate with Counter
用计数器枚举

获取索引值

作为 enumerate() 函数以元组格式返回,我们可以将索引和项放入单独的变量中,并在下面这样的循环中使用它们。

fruits=['apple','lemon','cherry','orange'] for index, item in enumerate(fruits):    print(index)    print(item)
Get Index Values
获取索引值

相关文章: 如何循环和迭代Python字典?

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享