sale_data = {
"95#": [150, 66, 523, 452],
"92#": [200, 452, 125, 689, 54],
"0#": [212, 548, 345]
}
final_res = {}
def sales_num(product_name):
total = 0
numbers = []
while True:
x = yield
if not x:
break
print(product_name + "的销量为:{}".format(x))
total += x
numbers.append(x)
return total, numbers
def middleware(product_name):
final_res[product_name] = yield from sales_num(product_name)
print(product_name + "统计完成!!!!")
def main():
global final_res, sale_data
for k, v in sale_data.items():
print(k, "开始统计")
m = middleware(k)
m.send(None) # 预激middleware委托生成器质性到yield from 处
for value in v:
m.send(value)
m.send(None)
print("统计结果为:", final_res)
if __name__ == '__main__':
main()
运行结果:
95# 开始统计
95#的销量为:150
95#的销量为:66
95#的销量为:523
95#的销量为:452
95#统计完成!!!!
Traceback (most recent call last):
File "C:/Users/Administrator/Desktop/python-test/code_97/chapter12/my_yield_from_test.py", line 66, in <module>
main()
File "C:/Users/Administrator/Desktop/python-test/code_97/chapter12/my_yield_from_test.py", line 61, in main
m.send(None)
StopIteration