给深度学习入门者的Python快速教程基础篇之十七
生成器(Generator)生成器是迭代器的一种,形式上看和函数很像,只是把return换成了yield,在每次调用的时候,都会执行到yield并返回值,同时将当前状态保存,等待下次执行到yield再继续:
# 从10倒数到0
def countdown(x):
while x >= 0:
yield x
x -= 1
for i in countdown(10):
print(i)
# 打印小于100的斐波那契数
def fibonacci(n):
a = 0
b = 1
while b < n:
yield b
a, b = b, a + b
for x in fibonacci(100):
print(x)
生成器和所有可迭代结构一样,可以通过next()函数返回下一个值,如果迭代结束了则抛出StopIteration异常:
a = fibonacci(3)
print(next(a)) # 1
print(next(a)) # 1
print(next(a)) # 2
print(next(a)) # 抛出StopIteration异常
Python3.3以上可以允许yield和return同时使用,return的是异常的说明信息:
# Python3.3以上可以return返回异常的说明
def another_fibonacci(n):
a = 0
b = 1
while b < n:
yield b
a, b = b, a + b
return "No more ..."
a = another_fibonacci(3)
print(next(a)) # 1
print(next(a)) # 1
print(next(a)) # 2
print(next(a)) # 抛出StopIteration异常并打印No more消息 6
页:
[1]