zoukankan      html  css  js  c++  java
  • Python3中简单的迭代器程序

    1.迭代器程序(实现菲比那次数列并且可以抛出与接收异常)

    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.利用迭代器实现简单的“单线程并行”吃包子(实际上还是串行)

    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')
    

      

  • 相关阅读:
    zencart_magiczoom
    如何把一个TXT文本文件按行数分割成多个文本文件
    工作时常用东西汇总
    asp Vernum
    sitemap制作
    php后门屌炸天
    威盾解密
    软路由
    企业安全工作要点
    内网ARP攻击
  • 原文地址:https://www.cnblogs.com/hjc4025/p/6508579.html
Copyright © 2011-2022 走看看