欢迎访问宙启技术站
智能推送

Python中的enumerate()函数详细介绍

发布时间:2023-06-09 02:13:11

Python中的enumerate()函数是一个极为方便的内置函数。它可以让我们在迭代一个可迭代对象时,同时获取该对象中每一个元素的下标。这个下标会随着迭代的进行而自动增加。

在一些需求中,我们需要记录每个元素的下标,这时候,使用enumerate()函数就比较方便了。

enumerate()函数的语法格式如下:

enumerate(sequence, [start=0])

参数:

sequence:表示一个序列、迭代器或其他支持迭代对象的对象。

start:表示起始下标(默认为0)。

返回值:

返回一个enumerate对象,里面包含了每个元素对应的下标以及元素本身。

下面来看一些实际使用的例子:

1、使用enumerate()函数遍历列表

我们可以通过以下方式使用enumerate()函数遍历列表:

fruits = ['apple', 'banana', 'orange', 'grape']
for index, fruit in enumerate(fruits):
    print(index, fruit)

输出结果:

0 apple
1 banana
2 orange
3 grape

2、使用enumerate()函数遍历字典

由于字典是无序的,当我们使用enumerate()函数遍历字典时,元素的下标不是按照插入顺序进行排序的。下面是一个使用enumerate()函数遍历字典的例子:

person = {'name': 'Tom', 'age': 18, 'gender': 'male'}
for index, key in enumerate(person):
    print(index, key, person[key])

输出结果:

0 name Tom
1 age 18
2 gender male

3、使用enumerate()函数指定起始下标

我们可以通过指定start参数来设置下标的起始位置。下面的例子设置了起始位置为2:

fruits = ['apple', 'banana', 'orange', 'grape']
for index, fruit in enumerate(fruits, start=2):
    print(index, fruit)

输出结果:

2 apple
3 banana
4 orange
5 grape

在实际开发中,enumerate()函数帮助我们遍历列表、元组、集合、字典等可迭代对象时,获取元素的下标,从而更加方便地进行后续的操作。