记录博客 ZH-BLOG

Python 协程

时间:2018-08-21 17:06:11分类:python

例一

>>> def gen1():
	for char in 'Python':
		yield char
	for i in range(5):
		yield i

		
>>> def gen2():
	yield from 'Python'
	yield from range(5)
	
>>> g1 = gen1()
>>> g2 = gen2()
>>> for x in g1:
	print(x, end=', ')

	
P, y, t, h, o, n, 0, 1, 2, 3, 4, 
>>> for x in g2:
	print(x, end=', ')

	
P, y, t, h, o, n, 0, 1, 2, 3, 4, 

例二

>>> def cities():
	for city in ['bj', 'hz', 'wh', 'sh']:
		yield city

>>> def squares():
	for number in range(5):
		yield number ** 2

		
>>> def all():
	for city in cities():
		yield city
	for number in squares():
		yield number

		
>>> def g_all():
	yield from cities()
	yield from squares()

	
>>> l1 = [e for e in all()]
>>> l1
['bj', 'hz', 'wh', 'sh', 0, 1, 4, 9, 16]
>>> l2 = [e for e in g_all()]
>>> l2
['bj', 'hz', 'wh', 'sh', 0, 1, 4, 9, 16]

例三

>>> def sub():
	yield 1
	yield 2
	return 42

>>> def dg():
	x = yield from sub()
	print('sub', x)

	
>>> for x in dg():
	print('main', x)

	
main 1
main 2
sub 42

例四

>>> def main():
	term = yield 1
	print('main', term)
	return 100

>>> def g():
	while True:
		print('gw')
		a = yield from main()
		print('g', a)

		
>>> g = g()
>>> next(g)
gw
1
>>> g.send(10)
main 10
g 100
gw
1
>>> g.send(20)
main 20
g 100
gw
1
>>> g.send(None)
main None
g 100
gw
1
>>> next(g)
main None
g 100
gw
1

例五

from collections import namedtuple

Result = namedtuple('Result', 'count average')

def averager():
    total = 0.0
    count = 0
    average = None
    while True:
        term = yield
        if term is None:
            break
        total += term
        count += 1
        average =  total/count
        return Result(count, average)


def grouper(results, key):
    while True:
        results[key] = yield from averager()
        

def main(data):
    results = {}
    for key, values in data.items():
        group = grouper(results, key)
        next(group)
        for value in values:
            group.send(value)
        # group.send(None)
        # print(results)
        report(results)


def report(results):
    for key, result in sorted(results.items()):
        group, unit = key.split(';')
        print('{:2} {:5} averaging {:.2f}{}'.format(result.count, group, result.average, unit))


data = {
    'girls;kg': [40.9, 38.5, 44.3, 42.2, 45.2, 41.7, 44.5, 38.0, 40.6, 44.5],
    'girls;m': [1.6, 1.51, 1.4, 1.3, 1.41, 1.39, 1.33, 1.46, 1.45, 1.43],
    'boys;kg':  [39.0, 40.8, 43.2, 40.8, 43.1, 38.6, 41.4, 40.6, 36.3],
    'boys;m': [1.38, 1.5, 1.32, 1.25, 1.37, 1.48, 1.25, 1.49, 1.46],
}


if __name__ == '__main__':
    main(data)