Skip to content

生成器函数:yield ​

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

for i in countdown(5):
    print(i)  # 5, 4, 3, 2, 1

生成器表达式 ​

python
squares = (x**2 for x in range(10))
print(next(squares))  # 0
print(next(squares))  # 1

练习:答案

用心记录每一步成长