python学习笔记---生成器

生成器

# 生成器

# 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)

while True:
    try:
        print(g.__next__())
    except StopIteration:
        print('end')
        break


g = (i**2 for i in range(5))

print(g.__next__())
# g.close()
print(g.__next__())


def gen():
    while True:
        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__())

0
2
4
6
True
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40
42
44
46
48
50
52
54
56
58
60
62
64
66
68
70
72
74
76
78
80
82
84
86
88
90
92
94
96
98
end
0
1
a
type error
a
fib数列生成器的实现
# 1. 当在函数中看到yield关键字, 那么这个函数调用的返回值是一个生成器;

def fib(num):
    a, b, count = 0, 1, 1  
    while 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__();从上一次停止的地方继续执行;
def fun():
    a = "world"
    print("hello")
    print(1)
    yield 2
    print(3)
    yield 4

g = fun()
print(g)

for i in g:    # g.__next__()
    print(i)

生产者消费者模型
import time
import random

def consumer(name):
    print("%s准备买包子....." %(name))
    while True:
        kind = yield
        print("%s已经购买%s口味包子....." %(name, kind))


def producer(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('小青')


小明准备买包子.....
小花准备买包子.....
厨师小青准备制作包子......
小青制作了特辣口味的包子
小明已经购买特辣口味包子.....
小花已经购买特辣口味包子.....
小青制作了微辣口味的包子
小明已经购买微辣口味包子.....
小花已经购买微辣口味包子.....
小青制作了三鲜口味的包子
小明已经购买三鲜口味包子.....
小花已经购买三鲜口味包子.....

猜你喜欢

转载自blog.csdn.net/qq_41891803/article/details/82149871