码迷,mamicode.com
首页 > 其他好文 > 详细

第四周练习 part3

时间:2018-04-04 23:36:25      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:com   生产者消费者模型   现在   read   练习   调用   方法   style   try   

列表生成式

# 列表生成式


a = [i * 2 for i in range(10)]
print(a)


def func(j):
    j = j / 2
    return j

b = [func(i) for i in range(100)]

for i in b:
    print(i)


c = (i * 2 for i in range(1000))
for i in c:
    if i < 530:
        print(i)

d = (i * 3 for i in range(10))
# 只有一个 next 方法,用的不多,一般都用循环调用
print(d.__next__())
print(d.__next__())
print(d.__next__())
print(d.__next__())

 

斐波那契数列

# 斐波那契数列,用函数生成
# 用函数做生成器,能够随时调用,中间可以干别的事,不必等待循环结束


def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b  # 原来是 print(b),为函数,现在是生成器
        a, b = b, a + b
        n = n + 1
    return done

f = fib(6)
# print(f)
# print(f.__next__())
# print(f.__next__())

while True:
    try:
        x = next(f)
        print(f:, x)
    except StopIteration as e:
        print(Generator return value:, e.value)
        break

# while True:
#     x = next(f)
#     print(‘f:‘, x)

 

多线程的实现

 1 # 生产者消费者模型,单线程实现并行效果
 2 
 3 import time
 4 
 5 
 6 def consumer(name):
 7     print(%s starts eating pizza! % name)
 8     while True:
 9         pizza = yield
10         print(Pizza [%s] is coming and eaten by [%s] % (pizza, name))
11 
12 
13 def producer(name):
14     c1 = consumer(A)  # 定义了生成器
15     c2 = consumer(B)
16     c1.__next__()  # 使执行生成器里的语句,遇到 yield 停止,执行 c2
17     c2.__next__()
18     print(Ready to make pizza!)
19     for i in range(5):
20         time.sleep(2)
21         print(%s Have made 2 Pizza % name)
22         c1.send(i)  # 回到 yield,将 i 传给了 pizza
23         c2.send(i)
24 
25 
26 producer(Lief)

 

第四周练习 part3

标签:com   生产者消费者模型   现在   read   练习   调用   方法   style   try   

原文地址:https://www.cnblogs.com/lief/p/8718856.html

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