生成器
创建生成器方法一
要创建⼀个⽣成器,有很多种⽅法。第⼀种⽅法很简单,只要把⼀个列表⽣成式的 [ ] 改成 ( )
In [1]: L = [x*2 for x in range(5)]
In [2]: L
Out[2]: [0, 2, 4, 6, 8]
In [3]: G = (x*2 for x in range(5))
In [4]: G
Out[4]: <generator object <genexpr> at 0x000001B281507A98>
创建 L 和 G 的区别仅在于最外层的 [ ] 和 ( ) , L 是列表,G 是生成器。我们可以直接打印出L的每个元素,但我们怎么打印出G的每个元素呢?使用next
函数
In [3]: G = (x*2 for x in range(5))
In [4]: G
Out[4]: <generator object <genexpr> at 0x000001B281507A98>
In [5]: next(G)
Out[5]: 0
In [6]: next(G)
Out[6]: 2
In [7]: next(G)
Out[7]: 4
In [8]: next(G)
Out[8]: 6
In [9]: next(G)
Out[9]: 8
In [10]: next(G)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-10-b4d1fcb0baf1> in <module>()
----> 1 next(G)
⽣成器保存的是算法,每次调⽤ next(G) ,就计算出 G 的下⼀个元素的值,直到计算到最后.个元素,没有更多的元素时,抛出 StopIteration 的异常。当然,这种不断调⽤ next()实在是太变态了,正确的⽅法是使⽤ for 循环,因为⽣成器也是可迭代对象。所以,我们创建了⼀个⽣成器后,基本上永远不会调⽤ next(),而是通过for循环来迭代它,并且不需要关心StopIteration 异常!
创建生成器方法二
先看看这个斐波那契函数的例子:
In [3]: def creatNum():
...: a,b = 0,1
...: for i in range(5): # 生成5个斐波那契数
...: print(b)
...: a,b = b,a+b
...:
In [4]: creatNum()
接下来我们把它改成生成器:
#-*- coding:utf-8 -*-
def creatNum():
print("---start---")
a,b = 0,1
for i in range(5):
print("---1---")
yield b
print("---2---")
a,b = b,a+b
print("---3---")
print("---stop---")
接下来我们将这个模块导入:
In [1]: from test import *
In [2]: a = creatNum()
In [3]: next(a)
---start---
---1---
Out[3]: 1
In [4]: next(a)
---2---
---3---
---1---
Out[4]: 1
In [5]: next(a)
---2---
---3---
---1---
Out[5]: 2
我们在循环过程中不断调⽤ yield ,就会不断中断。当然要给循环设置⼀个条件来退出循环,不然就会产⽣⼀个⽆限数列出来。同样的,把函数改成generator后,我们基本上从来不会⽤ next() 来获取下⼀个返回值,⽽是直接使⽤ for 循环来迭代!
In [1]: from test import *
In [2]: a = creatNum()
In [3]: while True:
...: try:
...: print("value:%d" % next(a))
...: except StopIteration as e:
...: print("生成器返回值:%s" % e.value)
...: break
...:
---start---
---1---
value:1
---2---
---3---
---1---
value:1
---2---
---3---
---1---
value:2
---2---
---3---
---1---
value:3
---2---
---3---
---1---
value:5
---2---
---3---
---stop---
生成器返回值:None
注意:next(a)
与a.__next__()
是等价的
send
In [1]: def test():
...: i = 0
...: while i<5:
...: tmp = yield i
...: print(tmp)
...: i += 1
...:
In [2]: t = test()
In [3]: t.__next__()
Out[3]: 0
In [4]: t.__next__()
None
Out[4]: 1
In [5]: t.__next__()
None
Out[5]: 2
为什么会打印出None呢?是应为yield i
执行完毕之后会把结果直接返回,但是不会赋值给tmp,所以每次打印都是None,此时使用send方法就会在yield i
执行完毕之并返回结果之后给yield i
赋值:
In [1]: def test():
...: i = 0
...: while i<5:
...: tmp = yield i
...: print(tmp)
...: i += 1
...:
In [2]: t = test()
In [3]: t.__next__()
Out[3]: 0
In [4]: t.__next__()
None
Out[4]: 1
In [5]: t.__next__()
None
Out[5]: 2
In [6]: t.send("Hello")
Hello
Out[6]: 3
In [7]: t.send("HelloWorld")
HelloWorld
Out[7]: 4
send的注意事项
In [8]: def test():
...: ...: i = 0
...: ...: while i<5:
...: ...: tmp = yield i
...: ...: print(tmp)
...: ...: i += 1
...: ...:
...:
In [9]: a = test()
In [10]: a.send("---")
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-dc33d05574fa> in <module>()
----> 1 a.send("---")
TypeError: can't send non-None value to a just-started generator
不能在第一次生成的时候就调用send方法,因为代码还未执行到yield i
,所以要先使用__next()__
,再使用send()
当然还有一个方法:
In [11]: def test():
...: ...: i = 0
...: ...: while i<5:
...: ...: tmp = yield i
...: ...: print(tmp)
...: ...: i += 1
...: ...:
...:
In [12]: t = test()
In [13]: t.send(None)
Out[13]: 0
总结
生成器是这样一个函数,它记住上一次返回时在函数体中的位置。对生成器函数的第二次(或者第n次)调用跳转至该函数体中间,而上次调用的所有局部变量都保持不变!
⽣成器不仅“记住”了它数据状态;⽣成器还“记住”了它在流控制构造(在命令式编程中,这种构造不只是数据值)中的位置
生成器的特点
- 节约内存,在超大列表的情况下是非常吃内存的!
- 迭代到下⼀次的调⽤时,所使⽤的参数都是第⼀次所保留下的,即是说,在整个所有函数调⽤的参数都是第⼀次所调⽤时保留的,⽽不是新创建的,这样非常高效!