python生成一个可以被遍历的函数,听起来很绕口,到底什么意思,就是可以把一个函数当成列表一样可以进行遍历,下面的代码中,函数每次运行生成的值都不一样,如果不设置终止次数,则会永远的遍历下去,看了这段代码,真实感到了python的强大
def fibonacci(start=(0, 1), stop=10): """Generate an iterator on the first 'stop' Fibonacci numbers, starting with the optional pair of numbers given as an argument. """ a, b = start while stop: yield a # the magic happens here. # yield acts like return, but control resumes there # on the next iteration a, b = b, a + b stop -= 1 for num in fibonacci(): print num