这是我的1 generator -- multiple consumers问题的后续问题。由于StopIteration
是生成器发出耗尽信号的方式,不幸的是,我现在在client
代码中有许多异常处理代码(对于下面示例中的每个next()
语句)。你知道吗
有没有更好的方法可以在遇到第一个StopIteration
异常时使用meal
中内置的值退出?你知道吗
def client(course, take):
meal = []
for _ in range(take):
try:
some_meal = next(course)
meal.append(some_meal)
except StopIteration:
pass
if take % 2 == 0:
try:
some_meal = next(course)
meal.append(some_meal)
except StopIteration:
pass
return meal
更新最终,我使用了'itertools.islice公司'(请参阅下面接受的解决方案),因为此函数负责StopIteration
本身(请参阅itertools
文档中所示的for
-循环等效实现)。与使用next
默认第二个参数相比,我更喜欢这个解决方案,因为它意味着要检查每个meal
(不过,与上面所有的异常处理相比,我最好使用后者)。你知道吗
除了使用
islice
之外,如果我正确地阅读了代码,那么它可以变得更简单:只需在第一个异常处理程序中直接返回:
尽管我仍然在这里更多地使用标准库,而且不必捕捉那些
StopIteration
异常:相关问题 更多 >
编程相关推荐