Python使用yield和send的用法

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

基本版:

def old_fib(n):
    res = [0] * n
    index = 0
    a = 0
    b = 1
    while index<n:
        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<n:
        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 <n:
        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 <n:
        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秒
复制完成
    原文作者:小小酥XX
    原文地址: https://www.jianshu.com/p/25496e9dc989
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞