码迷,mamicode.com
首页 > 编程语言 > 详细

python异常与生成器

时间:2018-05-14 10:22:36      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:唤醒   func   print   font   while   ret   bsp   time   消费   

列表生成器:

[ i*2 for i in range(10) ]这不是是生成器

[ func(i) for i in range(10) ]

( i*2 for i in range(10) ) 这就是生成器

 

一个算法,一个函数,可以边循环边生成数据,为了省空间,只有调用才会生成相应的数据。

只有__next()__方法

也可以用函数做个生成器

def fib(max):
    n,a,b = 0,0,1
    while n < max:
        print(b)
        a,b = b,a+b
        n = n + 1
    return ‘done‘
fib(10)


def fib(max):
    n,a,b = 0,0,1
    while n < max:
        yield(b)
        a,b = b,a+b
        n = n + 1
    return ‘done‘
print(fib(10))

fib_gen = fib(100)
print(fib_gen.__next__())
print(fib_gen.__next__())
print(fib_gen.__next__())

异常的捕获

def fib(max):
n,a,b = 0,0,1
while n < max:
yield(b)
a,b = b,a+b
n = n + 1
return ‘done‘
print(fib(10))

fib_gen = fib(10)
print(fib_gen.__next__())
print(fib_gen.__next__())
print(fib_gen.__next__())
print(fib_gen.__next__())
print(fib_gen.__next__())
print(fib_gen.__next__())
print(fib_gen.__next__())
print(fib_gen.__next__())
print(fib_gen.__next__())
while True:
try:
print(fib_gen.__next__())
except StopIteration as e:
print("Generator return value:",e.value)
break

也可以这样

def fib(max):
n,a,b = 0,0,1
while n < max:
yield(b)
a,b = b,a+b
n = n + 1
return ‘done‘
print(fib(10))

fib_gen = fib(10)

while True:
try:
print(fib_gen.__next__())
except StopIteration as e:
print("Generator return value:",e.value)
break

 

生产者与消费者

import time
def consumer(name):
print("%s准备吃包子"%name)
while True:
baozi = yield
print("包子[%s]来了,被[%s]吃了!"%(baozi,name))

c = consumer("Roger")
c.__next__();
baozi = "肉包子"
c.send(baozi)

send唤醒generator且给yield发送指
__next()只是唤醒generator,走到yield处,中断,返回
继续
import time
def consumer(name):
print("%s准备吃包子"%name)
while True:
baozi = yield
print("包子[%s]来了,被[%s]吃了!"%(baozi,name))

c = consumer("Roger")
c.__next__();
baozi = "肉包子"
c.send(baozi)
def producer(name):
c = consumer(‘A‘)
c2 = consumer(‘B‘)
c.__next__()
c2.__next__()
print("我开始准备做包子啦")
for i in range(10):
time.sleep(1)
print("做了2个包子")
c.send(i)
c2.send(i)
producer("alex")

生成器可以实现,单线程下的并行效果

携程

 

 

  

 

python异常与生成器

标签:唤醒   func   print   font   while   ret   bsp   time   消费   

原文地址:https://www.cnblogs.com/wherewhenwho/p/9034488.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!