本文目录导读:

我来为你介绍Python中使用for循环遍历各种数据类型的经典案例。
遍历列表(list)
# 基础遍历
fruits = ['苹果', '香蕉', '橙子', '葡萄']
for fruit in fruits:
print(fruit)
# 带索引遍历
for index, fruit in enumerate(fruits):
print(f"第{index+1}个水果是:{fruit}")
# 使用range遍历索引
for i in range(len(fruits)):
print(fruits[i])
遍历字典(dict)
# 学生成绩示例
scores = {'张三': 95, '李四': 88, '王五': 92}
# 遍历键
for name in scores:
print(f"学生:{name}")
# 遍历键值对
for name, score in scores.items():
print(f"{name}的分数是:{score}")
# 只遍历值
for score in scores.values():
print(f"分数:{score}")
遍历字符串
text = "Hello Python"
# 逐字符遍历
for char in text:
print(char, end=' ')
# 带索引遍历
for i, char in enumerate(text):
print(f"位置{i}的字符:{char}")
遍历元组(tuple)
# 坐标点示例
points = (10, 20, 30, 40, 50)
for point in points:
print(f"坐标值:{point}")
# 解包元组列表
coordinates = [(1, 2), (3, 4), (5, 6)]
for x, y in coordinates:
print(f"x={x}, y={y}")
遍历集合(set)
# 去重后的数字集合
numbers = {1, 2, 3, 2, 1, 4, 5}
print("集合中的元素:")
for num in numbers:
print(num)
# 注意:集合是无序的,遍历顺序可能不确定
多层循环遍历
# 二维列表遍历
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for element in row:
print(element, end=' ')
print() # 换行
# 乘法表
for i in range(1, 10):
for j in range(1, i+1):
print(f"{j}x{i}={i*j}", end='\t')
print()
实用案例:数据处理
# 学生成绩处理
students = [
{'name': '张三', 'scores': [85, 92, 78]},
{'name': '李四', 'scores': [90, 88, 95]},
{'name': '王五', 'scores': [70, 85, 80]}
]
print("学生成绩统计:")
for student in students:
name = student['name']
scores = student['scores']
total = sum(scores)
avg = sum(scores) / len(scores)
print(f"{name}: 总分={total}, 平均分={avg:.1f}")
带条件的遍历
# 过滤偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("偶数列表:")
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)
# break和continue示例
for num in range(1, 20):
if num == 10:
break # 遇到10停止
if num % 3 == 0:
continue # 跳过3的倍数
print(num, end=' ')
遍历文件内容
# 读取文件(假设有data.txt文件)
try:
with open('data.txt', 'r', encoding='utf-8') as file:
for line_number, line in enumerate(file, 1):
print(f"第{line_number}行:{line.strip()}")
except FileNotFoundError:
print("文件不存在")
实用技巧:zip并行遍历
# 并行遍历多个列表
names = ['张三', '李四', '王五']
ages = [25, 30, 28]
cities = ['北京', '上海', '深圳']
for name, age, city in zip(names, ages, cities):
print(f"{name},{age}岁,来自{city}")
这些案例涵盖了Python中最常见的遍历场景,实际开发中,根据不同的数据结构选择合适的遍历方式可以提高代码效率,记住使用enumerate()获取索引,items()遍历字典,以及zip()并行遍历多个序列都是很实用的技巧。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播