搜索

即使没有迭代,next 函数也很有用。将生成器表达式传递给 next 是一种快速搜索匹配某个谓词的元素的第一次出现的方法。程序代码就好

def find_and_transform(sequence, predicate, func):
    for element in sequence:
        if predicate(element):
            return func(element)
    raise ValueError

item = find_and_transform(my_sequence, my_predicate, my_func)

可以替换为:

item = next(my_func(x) for x in my_sequence if my_predicate(x))
# StopIteration will be raised if there are no matches; this exception can
# be caught and transformed, if desired.

为此,可能需要创建别名(如 first = next)或包装函数来转换异常:

def first(generator):
    try:
        return next(generator)
    except StopIteration:
        raise ValueError