for 循环
for 循环用于遍历序列(如列表、元组、字符串等)中的元素,或者执行指定次数的重复操作。它是 Python 中最常用的循环结构之一。
基本语法
for 循环的基本语法如下:
for item in iterable:
# 对每个 item 执行这里的代码
其中 iterable 是一个可迭代对象,如列表、元组、字符串或范围对象。item 是每次循环中从 iterable 中取出的一个元素。
遍历列表
for 循环最常见的用法是遍历列表中的元素。例如:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
输出:
apple
banana
cherry
使用 range() 函数
range() 函数生成一个整数序列,常用于需要执行固定次数的操作。例如:
for i in range(5):
print(i)
输出:
0
1
2
3
4
你还可以指定起始值、结束值和步长:
for i in range(1, 10, 2):
print(i)
输出:
1
3
5
7
9
遍历字典
for 循环也可以用于遍历字典中的键、值或键值对。例如:
person = {"name": "Alice", "age": 25, "city": "New York"}
# 遍历键
for key in person:
print(key)
# 遍历值
for value in person.values():
print(value)
# 遍历键值对
for key, value in person.items():
print(f"{key}: {value}")
输出:
name
age
city
Alice
25
New York
name: Alice
age: 25
city: New York
嵌套的 for 循环
for 循环可以嵌套在另一个 for 循环内部,以实现更复杂的遍历逻辑。例如,你可以使用嵌套的 for 循环来遍历二维列表或矩阵。
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 循环在实际编程中有广泛的应用,例如:
- 数据处理:遍历数据集并进行计算或分析。
- 文件读取:逐行读取文件内容。
- 图形绘制:生成图形或图表时,遍历坐标点或颜色值。
通过灵活使用 for 循环,你可以高效地处理大量数据,简化代码逻辑,并提高程序的可读性和可维护性。