• python 生成器与协程


    生成器在迭代中以某种方式生成下一个值并且返回和next()调用一样的东西。

    挂起返回出中间值并多次继续的协同程序被称作生成器。

    语法上讲,生成器是一个带yield语句的函数。一个函数或者子程序只返回一次,但一个生成器能暂停执行并返回一个中间的结果。

    随机数生成器实例:

    from random import randint
    def Mygen(alist):
        while len(alist) > 0:
            c = randint(0, len(alist)-1)
            yield alist.pop(c)
    
    a = ["ss","dd","gg"]
    
    for i in Mygen(a):
        print i
    
    
    #output
    #dd
    #gg
    #ss

    协程:

    使用send()为协程发送某个值之前,协程会暂时的中止,此时,协程中的yield表达式将会返回这个值,而接下来的语句将会处理它。处理直到遇到下一个yield表达式才会结束,也就是函数暂时中止的地方。close()生成器则退出。

    def Count(n):
        count = n
        while True:
            val = (yield count)
            if val is not None:
                count = val
            else:
                count += 1
    
    
    a = Count(10)
    print a.next()
    print a.next()
    a.send(5)
    print a.next()
    print a.next()
    a.close()
    print a.next()
    
    #/usr/bin/python /Users/li/PycharmProjects/Nowcoder_Practice/tmp.py
    #10
    #Traceback (most recent call last):
    #11
    #6
    #7
    #  File "/Users/li/PycharmProjects/Nowcoder_Practice/tmp.py", line 37, in <module>
    #    print a.next()
    #StopIteration
    
    #Process finished with exit code 1
  • 相关阅读:
    Beyond Compare 30天评估期已过解决方案
    windows快捷键及命令
    表情包的转码解码
    html+css实现文本从右向左
    js控制页面滚回上一记录位置
    将base64转为二进制
    牛客挑战赛58
    字符串专题
    牛客挑战赛59
    组合数学专题
  • 原文地址:https://www.cnblogs.com/lirunzhou/p/5881310.html
Copyright © 2020-2023  润新知