我们讲过,generator保存的是算法,每次调用next(g) 就计算出g 的下一个元素的值,直到计算到最后一个元素,没有更多的元素时,抛出stopIteration 的错误
当然,上面这种不断调用 next(g) 实在是太变态了,正确的方法是使用for循环,因为generator也是可迭代对象:
>>> g = (x*x for x in range(10))
>>> for n in g:... print(n)...0149162536496481>>>所以,我们创建了一个generator后,基本上永远不会调用next(),而是通过for循环来迭代它,并且不需要关心StopIteration的错误。
generator非常强大。如果推算的算法比较复杂,用类似列表生成式的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' 注意,赋值语句: a,b = b, a+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' print(fib(10)) 执行结果:
def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a+b n = n + 1 return 'done' f = fib(10) print(fib(10)) print(next(f)) print(next(f)) print(next(f)) print(next(f)) print(next(f)) print(next(f)) 执行结果:1 1 2 3 5 8 for i in f: print(i) 执行结果: 1 1 2 3 5 8 13 21 34 55 yield b #把函数的执行过程冻结在这一步,并且把B的值 返回给外面的next()