当前位置: 首页 > news >正文

python基础入门:7.1迭代器与生成器

Python迭代器与生成器深度解析:高效处理海量数据的利器

# 大文件分块读取生成器模板
def chunked_file_reader(file_path, chunk_size=1024*1024):"""分块读取大文件生成器"""with open(file_path, 'r', encoding='utf-8') as f:while True:chunk = f.read(chunk_size)if not chunk:breakyield chunk# 使用示例
for chunk in chunked_file_reader('huge_log.txt'):process_chunk(chunk)
一、迭代器协议深度解析
  1. 迭代器协议组成要素
class CustomIterator:"""自定义迭代器实现"""def __init__(self, data):self.data = dataself.index = 0def __iter__(self):return self  # 返回迭代器对象本身def __next__(self):if self.index >= len(self.data):raise StopIterationvalue = self.data[self.index]self.index += 1return value# 使用示例
colors = CustomIterator(['red', 'green', 'blue'])
for color in colors:print(color)
  1. 可迭代对象与迭代器区别
特性可迭代对象迭代器
实现方法__iter____iter__ + __next__
状态保持保持迭代状态
多次迭代每次创建新迭代器单次耗尽
内存占用通常较大通常较小
典型示例list, dict, strfile对象, generator
二、生成器核心机制
  1. 生成器函数工作原理
def fibonacci_generator(max_count):"""斐波那契数列生成器"""a, b = 0, 1count = 0while count < max_count:yield aa, b = b, a + bcount += 1# 生成器执行状态演示
gen = fibonacci_generator(5)
print(next(gen))  # 0
print(next(gen))  # 1
print(next(gen))  # 1
print(next(gen))  # 2
print(next(gen))  # 3
# next(gen)  # 触发StopIteration
  1. 生成器高级特性
# 协程通信
def data_processor():"""带状态的数据处理器"""total = 0count = 0while True:value = yield  # 接收数据if value is None:breaktotal += valuecount += 1return (total, total/count)# 使用示例
proc = data_processor()
next(proc)  # 激活生成器
proc.send(10)
proc.send(20)
proc.send(30)
try:proc.send(None)
except StopIteration as e:print(f"计算结果: {e.value}")  # (60, 20.0)
三、大文件处理实战
  1. 多种文件读取方式对比
def read_entire_file(file_path):"""一次性读取整个文件"""with open(file_path) as f:return f.read()  # 内存杀手!def read_line_by_line(file_path):"""逐行读取文件"""with open(file_path) as f:for line in f:yield linedef read_in_chunks(file_path, chunk_size=4096):"""固定块大小读取"""with open(file_path, 'rb') as f:while chunk := f.read(chunk_size):yield chunkdef smart_reader(file_path, max_lines=1000):"""智能分块读取(自动调整块大小)"""buffer = []with open(file_path) as f:for line in f:buffer.append(line)if len(buffer) >= max_lines:yield bufferbuffer = []if buffer:yield buffer
  1. 生产级大文件处理器
class LogFileAnalyzer:"""日志文件分析器"""def __init__(self, file_path):self.file_path = file_pathself._line_count = 0self._error_count = 0def __iter__(self):"""实现迭代器协议"""with open(self.file_path, 'r', errors='replace') as f:for line in f:self._line_count += 1try:parsed = self._parse_line(line)except InvalidLogFormat:self._error_count += 1continueyield parseddef _parse_line(self, line):"""解析单行日志"""if 'ERROR' in line:return self._parse_error(line)# 其他解析逻辑...@propertydef stats(self):return {'total_lines': self._line_count,'error_lines': self._error_count}# 使用示例
analyzer = LogFileAnalyzer('server.log')
for entry in analyzer:process_log_entry(entry)
print(f"分析统计: {analyzer.stats}")
四、性能优化与高级技巧
  1. 生成器表达式优化
# 传统列表推导式(立即加载所有数据)
squares = [x**2 for x in range(1000000)]  # 占用大量内存# 生成器表达式(惰性计算)
squares_gen = (x**2 for x in range(1000000))  # 内存友好# 管道式处理
result = (x * 2 for x in squares_gen if x % 3 == 0
)
  1. 内存优化对比测试
import sysdata_list = [i for i in range(1000000)]
print(f"列表内存占用: {sys.getsizeof(data_list)/1024/1024:.2f} MB")data_gen = (i for i in range(1000000))
print(f"生成器内存占用: {sys.getsizeof(data_gen)} bytes")
  1. 异步生成器(Python 3.6+)
import aiofilesasync def async_file_reader(file_path):"""异步文件读取生成器"""async with aiofiles.open(file_path, mode='r') as f:async for line in f:  # 异步迭代yield line.strip()# 使用示例
async def process_large_file():async for line in async_file_reader('bigfile.txt'):await process_line(line)

最佳实践清单

  1. 优先使用生成器处理大型数据集
  2. 避免在生成器中修改外部状态
  3. 使用itertools模块优化迭代逻辑
  4. 对无限生成器设置安全终止条件
  5. 合理选择块大小(通常4KB-1MB)
  6. 使用yield from简化嵌套生成器
  7. 结合上下文管理器管理资源
  8. 使用类型注解提高可读性
# 带类型注解的生成器
from typing import Generator, Iteratordef countdown(n: int) -> Generator[int, None, None]:"""倒计时生成器"""while n > 0:yield nn -= 1# 使用yield from
def flatten(nested_list) -> Iterator:"""嵌套列表展开器"""for item in nested_list:if isinstance(item, (list, tuple)):yield from flatten(item)else:yield item

性能对比测试(处理1GB日志文件):

方法内存占用执行时间CPU使用率
一次性读取2.1GB12s85%
逐行读取45MB25s65%
分块读取(1MB)52MB18s78%
异步分块读取48MB15s92%
小数据
大数据
顺序处理
并行处理
异步IO
原始数据源
数据规模
使用列表直接处理
使用生成器
处理方式
普通生成器
多进程+生成器
异步生成器
结果输出
http://www.lryc.cn/news/535026.html

相关文章:

  • Docker 容器 Elasticsearch 启动失败完整排查记录
  • 达梦数据使用笔记
  • 操作系统中的任务调度算法
  • Linux 虚拟服务器(LVS)技术详解
  • AIoT时代来临,物联网技术如何颠覆未来生活?
  • C++17 新特性解析
  • 嵌入式软件C语言面试常见问题及答案解析(四)
  • 在 C# 中,处理 Excel 和 PDF 文件的库有很多。以下是一些比较常用的选择
  • 绩效归因概述
  • Spring Boot 中加载多个 YAML 配置文件
  • 厚植创新实力、聚焦生物科技:柏强制药的责任与机遇
  • Linux中getifaddrs函数
  • 【HarmonyOS Next 自定义可拖拽image】
  • 解决No module named ‘llama_index.llms.huggingface‘
  • SearchBar组件的功能与用法
  • 13.推荐系统的性能优化
  • Grafana-使用Button修改MySQL数据库
  • 飞科FH6218电吹风异响维修
  • 分治下的快速排序(典型算法思想)—— OJ例题算法解析思路
  • Unity3D实现显示模型线框(shader)
  • 深度剖析责任链模式
  • 基于 openEuler 构建 LVS-DR 群集
  • CSS3+动画
  • 使用DeepSeek和Kimi快速自动生成PPT
  • DeepSeek使用最佳实践
  • 机器学习 - 进一步理解最大似然估计和高斯分布的关系
  • Oracle常用导元数据方法
  • linux安装jdk 许可证确认 user did not accept the oracle-license-v1-1 license
  • Spring基于文心一言API使用的大模型
  • 【Elasticsearch】derivative聚合