简单来说,generator是一个能够返回迭代器对象的函数.
yield的使用:
在python中,当你定义一个函数,使用了yield关键字时,这个函数就是一个生成器,它的执行会和其他普通的函数有很多不同,函数返回的是一个对象,而不是你平常 所用return语句那样,能得到结果值。如果想取得值,那得调用next()函数,如:
c = h() #h()包含了yield关键字
#返回值
c.next()
每当调用一次迭代器的next函数,生成器函数运行到yield之处,返回yield后面的值且在这个地方暂停,所有的状态都会被保持住,直到下次next函数被调用,或者碰到异常循环退出(也就是说,yield一般是放在循环里面的)。
def fib(max): a, b = 1, 1 while a < max: yield a #generators return an iterator that returns a stream of values. a, b = b, a+b
程序运行:
for n in fib(15): print n
yield其他例子展示:排列,组合
#生成全排列
def perm(items, n = None): if n is None: n = len(items) for i in range(len(items)): v = items[i:i+1] if n==1: yield v else: rest = items[:i] + items[i+1:] for p in perm(rest, n-1): yield v + p
def comb(items, n = None): if n is None: n = len(items) else: for i in range(len(items)): v = items[i:i+1] if 1 == n: yield v else: rest = items[i+1:] for c in comb(rest, n-1): yield v + c
上面这两个例子写的真好。
我自己实验了一下,发现生成全排列好使,但是生成组合的好像没啥用。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def perm(items, n = None): if n is None: n = len(items) for i in range(len(items)): v = items[i:i+1] if n==1: yield v else: rest = items[:i] + items[i+1:] for p in perm(rest, n-1): yield v + p def comb(items, n = None): if n is None: n = len(items) for i in range(len(items)): v = items[i:i+1] if 1 == n: yield v else: rest = items[i+1:] for c in comb(rest, n-1): yield v + c def main(): items = [1,2,3] for x in perm(items): print x print '-' * 20 for x in comb(items): print x if __name__ == '__main__': main()
结果:
$ python generator_demo.py [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1] -------------------- [1, 2, 3]