python怎么循环遍历列表

40次阅读
没有评论

共计 438 个字符,预计需要花费 2 分钟才能阅读完成。

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

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-13发表,共计438字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)