跳转至

迭代、推导式与生成器

迭代是 Python 的核心模式。for 可遍历 list、dict、文件对象和生成器等可迭代对象。

列表推导式适合简单的“映射 + 过滤”:

scores = [60, 80, 90]
passed = [score for score in scores if score >= 60]

逻辑复杂时使用普通循环,避免把多层条件塞进一行推导式。

生成器表达式使用圆括号,按需产生值,适合大数据流:

total = sum(score for score in scores if score >= 60)

生成器通常只能遍历一次。若后续还要重复使用结果,显式转换为 list 或重新创建生成器。

遍历字典键值对使用 items()

for key, value in user.items():
    print(key, value)

不要在遍历 dict 或 set 时直接增删其自身;先遍历副本或收集待变更项,否则可能抛出运行时错误。

参考

评论