搜尋

即使沒有迭代,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