Python 迭代器与生成器
学习 iter/next 和 yield 生成器 · 难度:高级 · +15XP
Python 迭代器与生成器
迭代器(Iterator)和生成器(Generator)是 Python 中处理序列数据的强大工具。它们支持惰性求值(Lazy Evaluation),即按需生成数据,而不是一次性将所有数据加载到内存中。这在处理大文件、无限序列和流式数据时尤为重要。
迭代器基础
迭代器是实现了 __iter__() 和 __next__() 方法的对象:
# 创建迭代器
numbers = [1, 2, 3, 4]
it = iter(numbers) # 获取迭代器对象
print(next(it)) # 1
print(next(it)) # 2
print(next(it)) # 3
print(next(it)) # 4
# print(next(it)) # StopIteration 异常
# for 循环自动处理迭代器
for item in iter(numbers):
print(item)
自定义迭代器
class CountDown:
"""倒计时迭代器"""
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
for num in CountDown(5):
print(num) # 5, 4, 3, 2, 1
生成器 (yield)
生成器是创建迭代器的最简洁方式,使用 yield 关键字:
# 生成器函数
def fibonacci(n):
"""生成前 n 个斐波那契数"""
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
for num in fibonacci(10):
print(num, end=' ')
# 输出: 0 1 1 2 3 5 8 13 21 34
# 生成器表达式 (类似列表推导式)
squares = (x ** 2 for x in range(10))
print(next(squares)) # 0
print(next(squares)) # 1
print(list(squares)) # [4, 9, 16, 25, 36, 49, 64, 81]
生成器的实际应用
# 读取大文件
def read_large_file(file_path):
"""逐行读取大文件,不占用大量内存"""
with open(file_path, 'r', encoding='utf-8') as f:
for line in f:
yield line.strip()
# 无限序列
def infinite_counter(start=0):
while True:
yield start
start += 1
counter = infinite_counter(10)
print(next(counter)) # 10
print(next(counter)) # 11
迭代器 vs 列表 对比表
| 特性 | 列表 (List) | 生成器 (Generator) |
|---|---|---|
| 内存使用 | 一次性加载全部数据 | 按需生成,内存高效 |
| 访问方式 | 可通过索引随机访问 | 只能顺序迭代一次 |
| 创建方式 | [] 或 list() | yield 或 () |
| 适用场景 | 数据量小,需多次访问 | 大数据量,流式处理 |
| len() 支持 | 支持 | 不支持 |