清單生成式
# 清單生成式
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')
轉載于:https://www.cnblogs.com/lief/p/8718856.html