# 生成10位fabnacci数列 deffab(): a,b=1,1 for i inrange(1,10): yield a a,b=b,a+b
console查看类型如下:
1 2 3 4 5
In [2]: fabnacci = fab()
In [3]: type(fabnacci) Out[3]: generator
打印数据:
1 2 3 4 5 6 7 8 9 10 11 12
In [6]: for i in fabnacci: print(i) 1 1 2 3 5 8 13 21 34
生产者消费者模型 协程
关于对生成器的应用,一个很好的例子是实现生产者消费者模型
执行由串行变成并行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
defconsumer(name): print("I'm crazy {name},I'm ready to kill some mother fucker.".format(name=name)) whileTrue: fucker = yield print('{name}:{fucker} guys has been killed.'.format(name=name,fucker=fucker))
defproducer(): tom = consumer('Tom') bob = consumer('Bob') next(tom) next(bob) for i inrange(1,10): tom.send(i) bob.send(i)
I'm crazy Tom,I'm ready to kill some mother fucker. I'm crazy Bob,I'm ready to kill some mother fucker. Tom:1 guys has been killed. Bob:1 guys has been killed. Tom:2 guys has been killed. Bob:2 guys has been killed. Tom:3 guys has been killed. Bob:3 guys has been killed. Tom:4 guys has been killed. Bob:4 guys has been killed. Tom:5 guys has been killed. Bob:5 guys has been killed. Tom:6 guys has been killed. Bob:6 guys has been killed. Tom:7 guys has been killed. Bob:7 guys has been killed. Tom:8 guys has been killed. Bob:8 guys has been killed. Tom:9 guys has been killed. Bob:9 guys has been killed.
可迭代对象和迭代器
可以迭代的主要分两种,一个是可迭代对象(Iterable)的和迭代器(Iterator)。
迭代器一定是可迭代对象,可迭代对象不一定是迭代器。
可迭代对象都可以用for x in xx:语句来遍历对象。
而迭代器还可以用next()函数逐个访问下一个值。遍历结束会遇到StopIteration异常。
可以看做迭代器是可迭代对象一个更高级的实现。
如何判断
可以用isinstance函数来查看。
记得先导入Iterable,Iterator。
1 2
from collections import Iterable from collections import Iterator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
In [19]: fabnacci = fab()
In [20]: a = [ x for x in range(1,10000)]
In [21]: isinstance(fabnacci,Iterable) Out[21]: True
In [22]: isinstance(fabnacci,Iterator) Out[22]: True