掌握Python中最常用的循环结构
Python中的for循环用于遍历序列(如列表、元组、字符串)或其他可迭代对象。
for 变量 in 序列:
# 循环体代码
# 每次循环,变量都会被赋值为序列中的下一个元素
# 遍历字符串
for letter in "Python":
print(letter)
# 输出结果:
# P
# y
# t
# h
# o
# n
列表是最常用的Python数据结构之一,for循环是遍历列表的主要方式。
fruits = ["苹果", "香蕉", "橙子", "葡萄"]
# 遍历列表
for fruit in fruits:
print(f"我喜欢吃{fruit}")
# 输出结果:
# 我喜欢吃苹果
# 我喜欢吃香蕉
# 我喜欢吃橙子
# 我喜欢吃葡萄
colors = ["红色", "绿色", "蓝色", "黄色"]
# 使用enumerate获取索引和值
for index, color in enumerate(colors):
print(f"索引 {index}: {color}")
# 输出结果:
# 索引 0: 红色
# 索引 1: 绿色
# 索引 2: 蓝色
# 索引 3: 黄色
enumerate()函数可以同时获取元素的索引和值,非常实用!
字典是Python中键值对的集合,for循环可以通过不同方式遍历字典。
student = {"姓名": "张三", "年龄": 20, "专业": "计算机科学"}
# 遍历键
for key in student:
print(key)
# 输出结果:
# 姓名
# 年龄
# 专业
person = {"name": "李四", "age": 25, "city": "北京"}
# 使用items()方法获取键值对
for key, value in person.items():
print(f"{key}: {value}")
# 输出结果:
# name: 李四
# age: 25
# city: 北京
range()函数生成一个整数序列,常用于for循环中指定循环次数。
# range()的三种用法 range(stop) # 0 到 stop-1 range(start, stop) # start 到 stop-1 range(start, stop, step) # 从start开始,步长为step
# 打印0到4
for i in range(5):
print(i, end=" ")
# 输出: 0 1 2 3 4
# 打印5到9
for i in range(5, 10):
print(i, end=" ")
# 输出: 5 6 7 8 9
# 打印0到10之间的偶数
for i in range(0, 11, 2):
print(i, end=" ")
# 输出: 0 2 4 6 8 10
# 从10倒序打印到1
for i in range(10, 0, -1):
print(i, end=" ")
# 输出: 10 9 8 7 6 5 4 3 2 1
# 从5到0
for i in range(5, -1, -1):
print(i, end=" ")
# 输出: 5 4 3 2 1 0
在循环内部再放置一个循环,称为嵌套循环。常用于处理多维数据结构。
# 打印九九乘法表
for i in range(1, 10): # 外层循环,控制行
for j in range(1, i+1): # 内层循环,控制列
print(f"{j}×{i}={i*j:2d}", end=" ")
print() # 换行
# 输出结果:
# 1×1= 1
# 1×2= 2 2×2= 4
# 1×3= 3 2×3= 6 3×3= 9
# ...
# 二维列表(矩阵)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# 遍历二维列表
for row in matrix: # 遍历每一行
for element in row: # 遍历当前行的每个元素
print(element, end=" ")
print() # 每行结束后换行
# 输出结果:
# 1 2 3
# 4 5 6
# 7 8 9
将for循环与其他Python特性结合使用,解决实际问题。
# 统计一句话中每个单词出现的次数
sentence = "hello world hello python world python programming"
words = sentence.split()
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 打印结果
for word, count in word_count.items():
print(f"单词 '{word}' 出现了 {count} 次")
# 输出结果:
# 单词 'hello' 出现了 2 次
# 单词 'world' 出现了 2 次
# 单词 'python' 出现了 2 次
# 单词 'programming' 出现了 1 次
# 学生成绩数据
students = [
{"name": "张三", "scores": [85, 92, 78]},
{"name": "李四", "scores": [76, 88, 95]},
{"name": "王五", "scores": [90, 85, 92]}
]
# 计算每个学生的平均分
for student in students:
name = student["name"]
scores = student["scores"]
total = 0
# 计算总分
for score in scores:
total += score
# 计算平均分
average = total / len(scores)
print(f"学生: {name}")
print(f" 各科成绩: {scores}")
print(f" 平均分: {average:.2f}")
print("-" * 30)
for-else结构:循环正常结束后执行else块zip()函数:同时遍历多个序列