Python3中简单的迭代器程序
1.迭代器程序(实现菲比那次数列并且可以抛出与接收异常)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def fib( max ): n,a,b = 0 , 0 , 1 while n < max : #print(b) yield b a,b = b,a + b n = n + 1 return 'done' g = fib( 10 ) while True : try : x = g.__next__() print ( 'g:' ,x) except StopIteration as e: print ( 'Generator return value:' ,e.value) break |
2.利用迭代器实现简单的“单线程并行”吃包子(实际上还是串行)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import time def consumer(name): print ( '[%s] prepare to eat baozi!!' % name) while True : baozi = yield print ( 'baozi [%s] is coming,ate by [%s]' % (baozi,name)) def producer(name): c = consumer( 'A' ) c2 = consumer( 'B' ) c.__next__() c2.__next__() print ( 'start' .center( 30 , '-' )) for i in range ( 10 ): time.sleep( 1 ) print ( 'just one,half to half' ) c.send(i) c2.send(i) producer( 'wt' ) |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步