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

 

posted @ 2016-09-18 13:35  赭山东路  阅读(1474)  评论(1编辑  收藏  举报