编程语言
首页 > 编程语言> > python yield from (一)

python yield from (一)

作者:互联网

1. yield from 会抛出iterator中所有的值;而yield只是抛出传进来的值,如果是值,就抛出值,如果是iterator对象,抛出iterator对象

def g1(iterable):
    yield iterable

def g2(iterable):
    yield from iterable

for value in g1(range(10)):
    print(value)
for value in g2(range(10)):
    print(value)

 

 

输出:

range(0, 10)
0
1
2
3
4
5
6
7
8
9

 

 

2. yield from会在调用方与子生成器之间建立一个双向通道

final_result = {}

def sales_sum(pro_name): # 子生成器
    total = 0
    nums = []
    while True:
        x = yield
        print(pro_name+"销量: ", x)
        if not x:
            break
        total += x
        nums.append(x)
    return total, nums

def middle(key): # 委托生成器
    while True:
        final_result[key] = yield from sales_sum(key)
        print(key+"销量统计完成!!.")

def main(): # 调用方
    data_sets = {
        "bobby牌面膜": [1200, 1500, 3000],
        "bobby牌手机": [28,55,98,108 ],
        "bobby牌大衣": [280,560,778,70],
    }
    for key, data_set in data_sets.items():
        print("start key:", key)
        m = middle(key)
        m.send(None) # 预激middle协程
        for value in data_set:
            m.send(value)   # 给协程传递每一组的值
        m.send(None)
    print("final_result:", final_result)

if __name__ == '__main__':
    main()

 

 

输出:

start key: bobby牌面膜
bobby牌面膜销量:  1200
bobby牌面膜销量:  1500
bobby牌面膜销量:  3000
bobby牌面膜销量:  None
bobby牌面膜销量统计完成!!.
start key: bobby牌手机
bobby牌手机销量:  28
bobby牌手机销量:  55
bobby牌手机销量:  98
bobby牌手机销量:  108
bobby牌手机销量:  None
bobby牌手机销量统计完成!!.
start key: bobby牌大衣
bobby牌大衣销量:  280
bobby牌大衣销量:  560
bobby牌大衣销量:  778
bobby牌大衣销量:  70
bobby牌大衣销量:  None
bobby牌大衣销量统计完成!!.
final_result: {'bobby牌面膜': (5700, [1200, 1500, 3000]), 'bobby牌手机': (289, [28, 55, 98, 108]), 'bobby牌大衣': (1688, [280, 560, 778, 70])}

 

标签:bobby,python,销量,yield,大衣,key,面膜
来源: https://www.cnblogs.com/callyblog/p/11185618.html