编程学习 /Python /进阶提高 /迭代器与生成器
🐍 Python 进阶提高

迭代器与生成器

搞懂 iter / next,再看看 yield 为什么能省内存。

📅 2026-11-23 👁 1 次阅读 🔗 根据 W3School Python 教程整理优化:https://www.w3school.com.cn/python/python_iterators.asp
迭代器与生成器示意图

可迭代对象和迭代器

nums = [1, 2, 3]       # 列表是可迭代对象
it = iter(nums)        # 拿到迭代器
print(next(it))        # 1
print(next(it))        # 2

取完会抛 StopIteration。for 循环内部其实就是自动帮你调用了 iter() 和 next()。

自己写一个迭代器

class Countdown:
    def __init__(self, start):
        self.cur = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.cur < 0:
            raise StopIteration
        v = self.cur
        self.cur -= 1
        return v

生成器更省事

def countdown(n):
    while n >= 0:
        yield n
        n -= 1

print(list(countdown(3)))   # [3, 2, 1, 0]
本站提示:生成器不会一次性把所有值装进内存,处理大文件或无限序列时特别有用。

本文根据 W3School Python 教程 的知识点重新整理、补充示例编写,非原文转载。