生成器:
1.只有在调用时才会生成相应的数据
2.只记录当前位置
3.使用__next__()方法调用
1 b=( i*2 for i in range(10)) 2 print(b.__next__()) 3 print(b.__next__()) 4 print(b.__next__())
结果:
使用生成器生成斐波拉契数列:
1 def fib(max): 2 n,a,b=0,0,1 3 while n<max: 4 yield b #yield函数返回当前状态b的值并中断 5 a,b=b,a+b 6 n+=1 7 return 'done'#异常时打印的信息 8 f=fib(10) 9 10 #异常处理,抓取代码错误并判断 11 while True: 12 try: 13 print(next(f)) 14 except StopIteration as e:#抓取StopIteration错误 15 print('Generator return value:',e.value) 16 break
运行结果:
运用生成器实现并行:
1 import time 2 def consumer(name1): 3 print('%s准备吃包子' % name1) 4 while True: 5 buns_stuffing=yield 6 print('一个%s馅包子被%s吃了' % (buns_stuffing,name1)) 7 8 # c=consumer('Tom') 9 # c.__next__()#调用yield 10 # c.send('韭菜')#调用yield并传值 11 # c.send('白菜') 12 13 def producer(name2): 14 c1=consumer('Tom') 15 c2=consumer('Bob') 16 c1.__next__()#通过next命令让consumer开始准备,走到yield中断 17 c2.__next__() 18 print('%s准备做包子' % name2) 19 list_of_bunstsuffing=['韭菜','白菜','芹菜'] 20 for suffing in list_of_bunstsuffing: 21 time.sleep(1) 22 print('做了两个%s馅的包子' % suffing) 23 c1.send(suffing) #发送 24 c2.send(suffing) 25 producer('Tao')
运行结果:
迭代器:
1.可以用于for循环的对象统称为可迭代对象:Iterable
2.可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。它表示惰性计算序列
3.生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator
4.把list、dict、str等Iterable变成Iterator可以使用iter()函数
5.Iterator对象是一个数据流,可被next()函数调用并返回下一个值。我们不知道整个序列的长度和下一个数据是多少只有需要时才会计算出下一个值
6.python中for循环本质就是通过不断调用next()函数实现的