Files
2025PY/day15/02-列表的遍历.py
2025-05-22 16:50:44 +08:00

31 lines
1.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 一、列表的遍历
# 列表是一个容器 可以存储多个数据 如果需要按照需求依次取出元素进行操作 那么就需要遍历
list=['apple','banana','orange','grape']
# 下标是有序的并且有规律的 使用循环进行操作
# len函数 获取列表的元素个数 通过len函数设置循环遍历的条件
# while循环
index=0
while index<len(list):
print(list[index])
index +=1
# for循环
for v in list:
print(v)
# 二、对比while循环和for循环
# while循环和for循环都是循环语句但细节不同
# 1.在循环条件控制上:
# while循环可以自定循环条件并自行控制
# for循环不可以自定循环条件,只可以一个个从容器内取出数据
# 2.在无限循环上:
# while循环可以通过条件控制做到无限循环
# for循环理论上不可以因为被遍历的容器容量不是无限的
# 3.在使用场景上:
# while循环适用于任何想要循环的场景
# for循环适用于遍历数据容器的场景 或 简单的固定次数循环场景