列表生成式
# 列表生成式
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