python - 自动将双向生成器推进到接受非无值的点?
问题描述
假设我们用 Python 编写了一个非常简单的双向生成器:
def share_of_total():
s = 0
new_num = 0
while True:
new_num = yield new_num / (s or 1)
s += new_num
share_calculator = share_of_total()
next(share_calculator) # Without this we get the TypeError
for num in [1, 2, 3]:
print(share_calculator.send(num))
这个生成器只接受一个数字并产生一个浮点数,表示它在所有先前提供的数字总和中所占的份额。
理想情况下,我们希望立即使用它,如下所示:
share_calculator = share_of_total()
print(share_calculator.send(num))
但是,这会导致TypeError: can't send non-None value to a just-started generator
. 的所有用户share_of_total()
必须记住next(share_calculator)
在生成器按预期使用之前执行。
有没有一种优雅的方式可以share_calculator
立即使用 - 即能够share_calculator.send(num)
在创建后立即调用share_calculator
?
解决方案
你应该用share_calculator.send(None)
将其包装在为您创建生成器的函数中:
def get_share_calculator():
def share_of_total():
s = 0
new_num = 0
while True:
new_num = yield new_num / (s or 1)
s += new_num
retval = share_total()
retval.send(None)
return retval
share_calculator = get_share_calculator()
for num in [1, 2, 3]:
print(share_calculator.send(num))
推荐阅读
- apache-kafka - Spring cloud Stream Kafka:获取processor.output().send(message)的确认;
- wordpress - Woocommerce - 如果在结帐期间登录,则删除所有旧购物车物品
- react-native - React-Native/Redux-Saga:如何等待调度完成
- xamarin - TabbedPage 上的 Retap 事件
- java - 使用 Log4j 为同一类分隔日志文件
- osgi - 如何在 OSGi 中编写工厂模式?
- sql - 截断和更新数据库表中的字符串值
- docker - Docker MailDev 中的电子邮件中的换行符
- reactjs - react-redux 桌面应用程序中请求的资源错误中不存在 Access-Control-Allow-Origin' 标头
- php - 如何在 .htaccess 的帮助下在 php 中重定向多个文件