Python高级特性——生成器
如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?这样就不必创建完整的list,从而节省大量的空间。在Python中,这种一边循环一边计算的机制,称为生成器:generator。
第一种方法很简单,只要把一个列表生成式的[]
改成()
,就创建了一个generator:
如果要一个一个打印出来,可以通过next()
函数获得generator的下一个返回值:
generator是非常强大的工具,在Python中,可以简单地把列表生成式改成generator,也可以通过函数实现复杂逻辑的generator。
要理解generator的工作原理,它是在for
循环的过程中不断计算出下一个元素,并在适当的条件结束for
循环。对于函数改成的generator来说,遇到return
语句或者执行到函数体最后一行语句,就是结束generator的指令,for
循环随之结束。
从这里开始,廖老师引用了斐波那契我就开始看不太懂了,而且代码也一直报错不知道为啥
廖老师的源代码如下:
要把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函数,调用一个generator函数将返回一个generator:
>>> f = fib(6)>>> f
这里,最难理解的就是generator函数和普通函数的执行流程不一样。普通函数是顺序执行,遇到return
语句或者最后一行函数语句就返回。而变成generator的函数,在每次调用next()
的时候执行,遇到yield
语句返回,再次执行时从上次返回的yield
语句处继续执行。
举个简单的例子,定义一个generator函数,依次返回数字1,3,5:
def odd(): print(\'step 1\') yield 1 print(\'step 2\') yield(3) print(\'step 3\') yield(5)
调用该generator函数时,首先要生成一个generator对象,然后用next()
函数不断获得下一个返回值:
>>> o = odd()>>> next(o)step 11>>> next(o)step 23>>> next(o)step 35>>> next(o)Traceback (most recent call last): File \"\", line 1, in StopIteration
可以看到,odd
不是普通函数,而是generator函数,在执行过程中,遇到yield
就中断,下次又继续执行。执行3次yield
后,已经没有yield
可以执行了,所以,第4次调用next(o)
就报错。
注意
调用generator函数会创建一个generator对象,多次调用generator函数会创建多个相互独立的generator。
有的童鞋会发现这样调用next()
每次都返回1:
>>> next(odd())step 11>>> next(odd())step 11>>> next(odd())step 11
原因在于odd()
会创建一个新的generator对象,上述代码实际上创建了3个完全独立的generator,对3个generator分别调用next()
当然每个都会返回第一个值。
正确的写法是创建一个generator对象,然后不断对这一个generator对象调用next()
:
>>> g = odd()>>> next(g)step 11>>> next(g)step 23>>> next(g)step 35
回到fib
的例子,我们在循环过程中不断调用yield
,就会不断中断。当然要给循环设置一个条件来退出循环,不然就会产生一个无限数列出来。
同样的,把函数改成generator函数后,我们基本上从来不会用next()
来获取下一个返回值,而是直接使用for
循环来迭代:
>>> for n in fib(6):... print(n)...112358
但是用for
循环调用generator时,发现拿不到generator的return
语句的返回值。如果想要拿到返回值,必须捕获StopIteration
错误,返回值包含在StopIteration
的value
中:
>>> g = fib(6)>>> while True:... try:... x = next(g)... print(\'g:\', x)... except StopIteration as e:... print(\'Generator return value:\', e.value)... break...g: 1g: 1g: 2g: 3g: 5g: 8Generator return value: done
关于如何捕获错误,后面的错误处理还会详细讲解。
练习
杨辉三角定义如下:
1 / \\ 1 1 / \\ / \\ 1 2 1 / \\ / \\ / \\ 1 3 3 1 / \\ / \\ / \\ / \\ 1 4 6 4 1 / \\ / \\ / \\ / \\ / \\1 5 10 10 5 1
把每一行看做一个list,试写一个generator,不断输出下一行的list:
def triangles(): pass# 期待输出:# [1]# [1, 1]# [1, 2, 1]# [1, 3, 3, 1]# [1, 4, 6, 4, 1]# [1, 5, 10, 10, 5, 1]# [1, 6, 15, 20, 15, 6, 1]# [1, 7, 21, 35, 35, 21, 7, 1]# [1, 8, 28, 56, 70, 56, 28, 8, 1]# [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]n = 0results = []for t in triangles(): results.append(t) n = n + 1 if n == 10: breakfor t in results: print(t)if results == [ [1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1], [1, 6, 15, 20, 15, 6, 1], [1, 7, 21, 35, 35, 21, 7, 1], [1, 8, 28, 56, 70, 56, 28, 8, 1], [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]]: print(\'测试通过!\')else: print(\'测试失败!\')
找到一个好理解一点的代码:
def factorial(num):
result = 1
for i in range(1, num + 1):
result *= i
return result
def triangles(): #Cn0 cn1 ... cnn
L = [[int(factorial(x)/(factorial(y)* factorial(x-y) ) ) for y in range(x+1)] for x in range(10)]
return L
# 期待输出:
# [1]
# [1, 1]
# [1, 2, 1]
# [1, 3, 3, 1]
# [1, 4, 6, 4, 1]
# [1, 5, 10, 10, 5, 1]
# [1, 6, 15, 20, 15, 6, 1]
# [1, 7, 21, 35, 35, 21, 7, 1]
# [1, 8, 28, 56, 70, 56, 28, 8, 1]
# [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
n = 0
results = []
for t in triangles():
results.append(t)
n = n + 1
if n == 10:
break
for t in results:
print(t)
if results == [
[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 4, 6, 4, 1],
[1, 5, 10, 10, 5, 1],
[1, 6, 15, 20, 15, 6, 1],
[1, 7, 21, 35, 35, 21, 7, 1],
[1, 8, 28, 56, 70, 56, 28, 8, 1],
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
]:
print(\'测试通过!\')
else:
print(\'测试失败!\')