扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

python中如何遍历列表

扬州沐宇科技
2024-01-14 05:46:58
python

在Python中,可以使用循环来遍历列表。常用的循环有for循环和while循环。

  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]
i = 0
while i < len(my_list):
    print(my_list[i])
    i += 1

输出:

1
2
3
4
5

可以看到,使用for循环更加简洁和直观,而while循环相对繁琐一些。因此,在遍历列表时,推荐使用for循环。

扫码添加客服微信