8. 生成器

创建一个生成器

>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x1022ef630>

创建L和g的区别仅在于最外层的 [] 和 (),L是一个list,而g是一个genetator。

list元素可以直接打印,怎么打印generator的每一个元素呢?------通过next()函数

>>> next(g)
0
>>> next(g)
1
>>> next(g)
4
>>> next(g)
9
>>> next(g)
16
>>> next(g)
25
>>> next(g)
36
>>> next(g)
49
>>> next(g)
64
>>> next(g)
81
>>> next(g)
Traceback (most recent call last):
	File "<stdin>", line 1, in <module>
StopIteration

没有更多的元素时,抛出StopIteration的错误。

第二种方法:使用for循环,因为generator也是可迭代对象:

>>> g = (x * x for x in range(10))
>>> for n in g:
... 	print(n)
...
0
1
4
9
16
25
36
49
64
81

如果推算的算法比较复杂,用类似列表生成式的for循环无法实现的时候,还可以用函数来实现。

比如,著名的斐波拉契数列(Fibonacci),除第一个和第二个数外,任意一个数都可由前两个数相加得到:1, 1, 2, 3, 5, 8, 13, 21, 34, ...,斐波拉契数列用列表生成式写不出来,但是,用函数把它打印出来却很容易:

def fib(max):
	n, a, b = 0, 0, 1
	while n < max:
		print(b)
		a, b = b, a + b
		n = n + 1
	return 'done'

要把fib函数变成generator,只需要把print(b)改为yield b就可以了:

def fib(max):
	n, a, b = 0, 0, 1
	while n < max:
		yield b
		a, b = b, a + b
		n = n + 1
	return 'done'

这就是定义generator的另一种方法。如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator:

>>> f = fib(6)
>>> f
<generator object fib at 0x104feaaa0>

generator函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。

把函数改成generator后,我们基本上从来不会用next()来获取下一个返回值,而是直接使用for循环来迭代:

>>> for n in fib(6):
...		print(n)
...
1
1
2
3
5
8

但是用for循环调用generator时,发现拿不到generatorreturn语句的返回值。如果想要拿到返回值,必须捕获StopIteration错误,返回值包含在StopIterationvalue中:

>>> g = fib(6)
>>> while True:
... 	try:
... 		x = next(g)
... 		print('g:', x)
... 	except StopIteration as e:
... 		print('Generator return value:', e.value)
... 		break
...
g: 1
g: 1
g: 2
g: 3
g: 5
g: 8
Generator return value: done
原文地址:https://www.cnblogs.com/BigMario/p/13577583.html