Python 生成器
Python 使用 yield 关键字来创建生成器。生成器相比列表具有使用内存小、可流式处理等优势。
使用 yield:
def process_file(file):
with open(file) as f:
for line in f:
yield process_line(line) # 对文件每一行进行处理并添加到生成器
data = process_file(file)
for record in data: # 可以像列表一样使用生成器
print(data)
相比于列表,生成器的一个优点是其中的数据只有被迭代到的时候才会加载,并且在使用过后马上被清理。因此迭代器占用的内存很小。
使用多个迭代器:
# 处理单个文件
def process_single_file(file):
with open(file) as f:
for line in f:
yield process_line(line) # 处理每一行
# 处理多个文件
def process_files(files):
for file in files:
yield from process_single_file(file) # 直接委托处理

浙公网安备 33010602011771号