# 生成器# 1. 列表生成式修改为生成器
li = [i for i in range(100) if i%2==0]
# 生成器
g = (i for i in range(100) if i%2==0)
# 2. 查看生成器内容的两种方式# 2-1.python3中 g.__next__方法(), python2.x中g.next();# python2.x, python3.x, next(g)
print(g.__next__())
print(g.__next__())
print(g.__next__())
print(next(g))
## 2-2. for循环# isinstance(1, int)# isinstance(1, (int, float))from collections import Iterable
print(isinstance(g, Iterable))
for i in g:
print(i)
whileTrue:
try:
print(g.__next__())
except StopIteration:
print('end')
break
g = (i**2for i in range(5))
print(g.__next__())
# g.close()
print(g.__next__())
defgen():whileTrue:
try:
yield'a'except TypeError:
print('type error')
# throw方法:给生成器发送一个异常(错误); 但是不影响g.__next__()的执行;# close(): 关闭生成器, 再次执行g.__next__()报错;
g = gen()
print(g.__next__())
g.throw(TypeError)
print(g.__next__())
0246
True
8101214161820222426283032343638404244464850525456586062646668707274767880828486889092949698end01a
type error
a
fib数列生成器的实现
# 1. 当在函数中看到yield关键字, 那么这个函数调用的返回值是一个生成器;deffib(num):
a, b, count = 0, 1, 1while count <= num:
yield b
a, b = b, a + b #a=2, b=3
count += 1
g = fib(10)
for i in g:
print(i)
1
1
2
3
5
8
13
21
34
55
yield理解
# 1. 当在函数中看到yield关键字, 那么这个函数调用的返回值是一个生成器;# 2. 当要执行函数fun时, 必须调用g.__next__();# 3. 函数执行时, 直到遇到yield停止;# 4. 想要继续执行, 调用g.__next__();从上一次停止的地方继续执行;deffun():
a = "world"
print("hello")
print(1)
yield2
print(3)
yield4
g = fun()
print(g)
for i in g: # g.__next__()
print(i)
生产者消费者模型
import time
import random
defconsumer(name):
print("%s准备买包子....." %(name))
whileTrue:
kind = yield
print("%s已经购买%s口味包子....." %(name, kind))
defproducer(name):
c1 = consumer("小明")
c2 = consumer("小花")
c1.__next__()
c2.__next__()
print("厨师%s准备制作包子......" %(name))
for kind in ['特辣', '微辣','三鲜']:
time.sleep(random.random())
print("%s制作了%s口味的包子" %(name, kind))
c1.send(kind)
c2.send(kind)
producer('小青')