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

使用Python的enumerate()函数循环遍历序列

发布时间:2023-06-17 17:19:04

enumerate() 函数是 Python 内置的一个非常方便的函数,它可以将一个可遍历的数据对象(如列表、元组等)组合成一个索引序列和一个元素数据序列,就像一个序列的键-值对。

enumerate() 函数的语法为:

enumerate(sequence, start=0)

其中,sequence 表示要循环遍历的序列对象,start 表示开始索引,默认为 0。

例如下面的代码:

fruits = ['apple', 'banana', 'cherry']
for index, value in enumerate(fruits):
    print(index, value)

输出结果为:

0 apple
1 banana
2 cherry

可以看出,enumerate() 函数返回的是一个可迭代的两个元素的 tuple 类型,其中第一个元素是序列的索引,第二个元素是序列的元素。

我们可以在循环遍历一个序列时,使用 enumerate() 函数来获取每个元素的索引和值,从而方便地进行其它操作。

下面是一个使用 enumerate() 函数循环遍历列表,并打印每个元素及其索引的示例:

numbers = [1, 2, 3, 4, 5]
for index, value in enumerate(numbers):
    print("Index:", index, "Value:", value)

输出结果为:

Index: 0 Value: 1
Index: 1 Value: 2
Index: 2 Value: 3
Index: 3 Value: 4
Index: 4 Value: 5

除了列表之外,我们还可以使用 enumerate() 函数遍历元组、字符串、字典等序列。

例如,下面是一个使用 enumerate() 函数遍历字符串,找出其中所有字母 'e' 的索引的示例:

string = "hello, world!"
for index, char in enumerate(string):
    if char == 'e':
        print("Index of 'e':", index)

输出结果为:

Index of 'e': 1
Index of 'e': 7

以上就是使用Python的enumerate()函数循环遍历序列的方法和示例。使用这个函数可以简洁地遍历序列并积极用于实际开发中。