python yield send_Python使用yield和send的用法

先看一段普通的计算斐波那契续列的代码:

基本版:

def old_fib(n):

res = [0] * n

index = 0

a = 0

b = 1

while index

res[index] = b

a,b = b,a+b

index += 1

return res #返回数组[]*n

print('-'*10 + '测试' + '-'*10)

for fib_res in old_fib(10):

print(fib_res)

结果:

----------测试----------

1

1

2

3

5

8

13

21

34

55

使用yield版:

def fib(n):

index = 0

a = 0

b = 1

while index

yield b #yield把结果b从函数扔出去

a, b = b, a + b

index += 1

print('-'*10 + '测试 yield' + '-'*10)

for fib_res in fib(10):

print(fib_res)

结果

----------测试 yield----------

1

1

2

3

5

8

13

21

34

55

使用send版:

import random

import time

def stupid_fib(n):

index = 0

a = 0

b = 1

while index

sleep_cnt = yield b #yield把结果b从函数扔出去,返回值用send接收过来

print('让我思考{0}秒'.format(sleep_cnt))

time.sleep(sleep_cnt)

a, b = b, a + b

index += 1

print('-'*10 + 'test yield send' + '-'*10)

N = 10

sfib = stupid_fib(N)

fib_res = next(sfib) #相当于sfib.send(None)

while True:

print(fib_res)

try:

fib_res = sfib.send(random.uniform(0, 0.5))

except StopIteration:

break

结果

----------测试 yield send----------

1

让我思考0.3726817450087525秒

1

让我思考0.25331633079776733秒

2

让我思考0.09393476884999097秒

3

让我思考0.3392211006197199秒

5

让我思考0.33262903389842274秒

8

让我思考0.41414110149962935秒

13

让我思考0.21604414711985792秒

21

让我思考0.025865695087244345秒

34

让我思考0.28991156481780744秒

55

让我思考0.263892230023429秒

使用yield from的用法:

import random

import time

def stupid_fib(n):

index = 0

a = 0

b = 1

while index

sleep_cnt = yield b #yield把结果b从函数扔出去,返回值用send接收过来

print('让我思考{0}秒'.format(sleep_cnt))

time.sleep(sleep_cnt)

a, b = b, a + b

index += 1

def copy_stupid_fib(n):

print('我是stupid_fib()的复制')

yield from stupid_fib(n)

print('复制完成')

print('-'*10 + '测试 yield from send' + '-'*10)

N = 10

csfib = copy_stupid_fib(N)

fib_res = next(csfib)

while True:

print(fib_res)

try:

fib_res = csfib.send(random.uniform(0, 0.5))

except StopIteration:

break

结果

----------测试 yield from send----------

我是stupid_fib()的复制

1

让我思考0.28898040867944874秒

1

让我思考0.46000191699833454秒

2

让我思考0.021769106639172697秒

3

让我思考0.20333080975901485秒

5

让我思考0.19305777011503833秒

8

让我思考0.09847006007411069秒

13

让我思考0.3013770267669208秒

21

让我思考0.13223476217553276秒

34

让我思考0.44592478930164614秒

55

让我思考0.0881971642022118秒

复制完成

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值