zoukankan      html  css  js  c++  java
  • python 基础(十六)生成器用法举例

    import  time
    def consumer(name):
        print('%s,准备吃包子'%name)
        while True:
            baozi = yield
            print('包子%s来了,被%s吃了'%(baozi,name))
    c = consumer('clyde')
    c.__next__()  #__next__():调用一次
    b = '香菇油菜馅'
    c.send(b) #send():把参数发送过去在调用一次

    协程

    import  time
    def consumer(name):
        print('%s,准备吃包子'%name)
        while True:
            baozi = yield
            print('包子%s来了,被%s吃了'%(baozi,name))
    c = consumer('clyde')
    c.__next__()
    def producer(name):
        c = consumer('张三')
        c2 = consumer('的歌')
        c.__next__()
        c2.__next__()
        print('我开始准备做包子了')
        for i in range(10):
            time.sleep(1)
            print('做了一个包子')
            c.send(i)
            c2.send(i)
    producer('name')
  • 相关阅读:
    Merge Two Sorted Lists
    4Sum
    Letter Combinations of a Phone Number
    3Sum Closest
    3Sum
    Longest Common Prefix
    Roman to Integer
    Integer to Roman
    Container With Most Water
    Regular Expression Matching
  • 原文地址:https://www.cnblogs.com/zbvc/p/13132259.html
Copyright © 2011-2022 走看看