Skip to content

Instantly share code, notes, and snippets.

@lttzzlll
Created April 28, 2018 14:49
Show Gist options
  • Save lttzzlll/dac7475e153f9a579b40bf65823d6a63 to your computer and use it in GitHub Desktop.
Save lttzzlll/dac7475e153f9a579b40bf65823d6a63 to your computer and use it in GitHub Desktop.
from collections import namedtuple
Result = namedtuple('Result', 'Count Averge')
def averger():
count = 0
total = 0
avg = None
while True:
term = yield avg
if term is None:
break
total += term
count += 1
avg = total / count
return Result(count, avg)
avger = averger()
avger.send(None)
for i in range(1, 11):
print(avger.send(i))
try:
res = avger.send(None)
except StopIteration as e:
res = e.value
print(res)
# 1.0
# 1.5
# 2.0
# 2.5
# 3.0
# 3.5
# 4.0
# 4.5
# 5.0
# 5.5
# Result(Count=10, Averge=5.5)
@lttzzlll
Copy link
Author

Python协程一个demo,注意获取最后值的方法,如果使用return语句,那么只能在 StopIteration.value中得到该值。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment