温馨提示×

python怎么循环遍历列表

小亿
206
2023-12-13 01:03:49
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:python如何用for循环遍历列表

0