生成器
生成器generator
- 生成器指的是生成器对象,可以由生成器表达式得到,也可以使用yield关键字得到一个生成器函数,调用这个函数得到一个生成器对象。
- 生成器对象,是一个可迭代对象,是一个迭代器
- 生成器对象,是延迟计算、惰性求值的
生成器函数
- 函数体中包含yield语句的函数,就是生成器函数,调用后返回生成器对象
m = (i for i in range(5)) #生成器表达式
print(type(m))
<class 'generator'>
print(next(m))
0
print(next(m))
1
def inc(): #生成器函数
for i in range(5):
yield i
print(type(inc))
<class 'function'>
print(type(inc()))
<class 'generator'>
g = inc()
print(type(g))
<class 'generator'>
print(next(g))
0
for x in g:
print(x)
print('--------------')
1
2
3
4
--------------
for y in g:
print(y)
没有打印
普通函数调用,函数会立即执行直到执行完毕
生成器函数调用,并不会立即执行函数体,而是需要使用next函数来驱动生成器函数执行后获得的生成器对象
生成器表达式和生成器函数都可以得到生成器对象,只不过生成器函数可以写的更加复杂的逻辑
生成器的执行
def gen():
print('line 1')
yield 1
print('line 2')
yield 2
print('line 3')
return 3
yield 4
next(gen())
line 1
1
next(gen())
line 1
1
g = gen()
next(g)
line 1
1
next(g)
line 2
2
next(g)
StopIteration 3
- 在生成函数中,可以多次yield,每次执行一次yield后会暂停执行,把yield表达式的值返回
- 再次执行会执行到下一个yield语句又会暂停执行
- return语句依然可以终止函数运行,但return语句的返回值不能被获取到
- return会导致当前函数返回,无法继续执行,也无法继续获取下一个值,抛出Stopiteration异常
- 如果函数没有正式的return语句,如果生成器执行到结尾(相当于执行return None),一样会抛出Stopiteration异常
生成器函数
- 包含yield语句的生成器函数调用后,生成生成器对象的时候,生成器函数的函数体不会立即执行
- next(generator)会从函数的当前位置向后执行到之后碰到的第一个yield语句,会弹出值,并暂停函数执行
- 再次调用next函数,和上一条一样的处理过程
- 继续调用next函数,生成器函数如果结束执行了(显式或隐式调用了return语句),会抛出Stopiteration异常
生成器应用
- 无线循环
def counter():
i = 0
while True:
i += 1
yield i
c = counter()
print(next(c))
1
print(next(c))
2
print(next(c))
3
- 计数器
def inc():
def counter():
count = 0
while True:
count += 1
yield count
c = counter()
return next(c)
这样每次打印的都是1因为,每次都是重新生成
print(inc())
1
print(inc())
1
def inc():
def counter():
count = 0
while True:
count += 1
yield count
c = counter()
return lambda :next(c)
# def inner(): 等价于 lambda :next(c)
# return next(c)
# return inner
foo = inc()
print(foo())
1
print(foo())
2
- 斐波那契数列
def fib():
x = 0
y = 1
while True:
yield y
x, y = y, x + y
foo = fib()
for i in range(5):
print(next(foo))
- 生成器交互
def inc():
def counter():
i = 0
while True:
i += 1
response = yield i
if response is not None:
i = response
c = counter()
return lambda x = False: next(c) if not x else c.send(0)
foo = inc()
print(foo())
1
print(foo())
2
print(foo(True))
1
调用send方法,就可以把send的实参传给yield语句做结果,这个结果可以在等式右边被赋值给其他变量
send和next一样可以推动生成器启动并执行
yield from语法
从python 3.3开始增加了yield from语法,使得yield from iterable 等价于 for item initerable:yield item
yield from 就是一种简化语法的语法糖
def inc():
for x in range(10000):
yield x
#使用了yield from简化
def inc_():
yield from range(10000)
foo = inc()
print(next(foo))
1
print(next(foo))
2
foo_ = inc_()
print(next(foo_))
1
print(next(foo_))
2