新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

python如何循环遍历列表,pythonfor循环遍历

发布时间:2023-12-13 01:03:49

python如何循环遍历列表

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

  1. 使用for循环:
my_list = [1, 2, 3, 4, 5]
for item in my_list:
    print(item)

输出:

1
2
3
4
5
  1. 使用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
  1. 使用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中经常使用的循环遍历列表的方法,根据实际需求选择合适的方法。