python怎么循环遍历列表

Python中有多种方式可以循环遍历列表,下面是三种常用的方法:

使用for循环:

my_list = [1, 2, 3, 4, 5]
for item in my_list:
    print(item)

输出:

1
2
3
4
5

使用while循环和索引:

my_list = [1, 2, 3, 4, 5]
index = 0
while index < len(my_list):
    print(my_list[index])
    index += 1

输出:

1
2
3
4
5

使用enumerate函数同时获取索引和值:

my_list = [1, 2, 3, 4, 5]
for index, item in enumerate(my_list):
    print(f"Index: {index}, Value: {item}")

输出:

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

以上是Python中常用的循环遍历列表的方法,根据实际需求选择适合的方法。

阅读剩余
THE END