Python在第一次StopIteration时退出使用者

2024-04-25 16:31:20 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的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(不过,与上面所有的异常处理相比,我最好使用后者)。你知道吗


Tags: 代码clientfor请参阅somepassnextitertools
2条回答

除了使用islice之外,如果我正确地阅读了代码,那么它可以变得更简单:

def client(course, take):
    if take % 2 == 0:
        take += 1
    return list(itertools.islice(course, take))

只需在第一个异常处理程序中直接返回:

def client(course, take):
    meal = []
    for _ in range(take):
        try:
            some_meal = next(course)
            meal.append(some_meal)
        except StopIteration:
            return meal
    if take % 2 == 0:
        try:
            some_meal = next(course)
            meal.append(some_meal)
        except StopIteration:
            pass
    return meal

尽管我仍然在这里更多地使用标准库,而且不必捕捉那些StopIteration异常:

from itertools import islice


def client(course, take):
    meal = list(islice(course, take))

    if take % 2 == 0:
        some_meal = next(course, None)
        if some_meal is not None:
            meal.append(some_meal)

    return meal

相关问题 更多 >