enumerate 是 Python 内置函数,用于同时遍历迭代对象的索引和元素。它返回一个枚举对象,其中每个元素都是一个包含索引和对应元素的元组。

下面是 enumerate 函数的基本用法:

for index, element in enumerate(iterable):
    # 使用 index 和 element 进行相应的操作

例如,我们有一个列表 fruits,希望打印出每个水果的索引和名称:

fruits = ['apple', 'banana', 'orange']

for index, fruit in enumerate(fruits):
    print(f'Index: {index}, Fruit: {fruit}')

输出结果:

Index: 0, Fruit: apple
Index: 1, Fruit: banana
Index: 2, Fruit: orange

通过 enumerate 函数,我们可以在遍历列表时同时获取索引和对应的元素值,这在很多情况下非常有用。

Python enumerate 函数:遍历索引和元素的利器

原文地址: https://www.cveoy.top/t/topic/XVM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录