📜  带有索引 python3 的 for 循环 - Python (1)

📅  最后修改于: 2023-12-03 15:39:26.878000             🧑  作者: Mango

带有索引 Python3 的 for 循环

在Python中,for循环可以用于遍历各种类型的序列,如字符串,列表,元组和字典。索引是标识序列中每个元素的位置,Python的for循环有一个特殊的功能,允许我们在循环中访问索引。

基本语法
for index, value in enumerate(sequence):
    # 循环体

该语法中,index代表当前元素的索引,value代表当前元素的值,而enumerate()是Python中的特殊函数,它将给定的序列转换为一个新的迭代器,每个元素将以(index, value)的方式返回。

示例

以下示例将使用for循环遍历一个列表,并输出每个元素及其索引:

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

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

输出:

Index 0: apple
Index 1: banana
Index 2: orange
Index 3: mango

在循环内部,我们使用f-string格式化字符串来打印当前元素的索引和值。注意索引从0开始计数。

我们还可以使用for循环访问元组,如下所示:

person = ('John', 'Doe', 30)

for index, value in enumerate(person):
    print(f"Index {index}: {value}")

输出:

Index 0: John
Index 1: Doe
Index 2: 30

此外,我们还可以使用带有start参数的enumerate()函数来指定从何处开始索引。例如,以下示例演示了如何从索引2开始遍历一个列表:

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

for index, fruit in enumerate(fruits, start=2):
    print(f"Index {index}: {fruit}")

输出:

Index 2: apple
Index 3: banana
Index 4: orange
Index 5: mango
总结

使用带有索引的for循环可以使我们在遍历序列时轻松访问元素的位置。此外,enumerate()函数的使用也使得代码更加简洁和易读。