从匹配条件的迭代器中获取第一项。

从匹配条件的迭代器中获取第一项。

我想从符合条件的列表中获得第一项。重要的是,生成的方法不能处理整个列表,这可能相当大。例如,以下功能就足够了:

def first(the_iterable, condition = lambda x: True):
    for i in the_iterable:
        if condition(i):
            return i

这个函数可以使用如下所示:

>>> first(range(10))0>>> first(range(10), lambda i: i > 3)4

然而,我想不出一个好的内置/一个班轮让我这样做。如果没有必要的话,我不特别想复制这个函数。是否有一个内置的方式,以获得第一个项目匹配的条件?


猛跑小猪
浏览 669回答 3
3回答

POPMUISE

作为一个可重用、文档化和测试的功能def first(iterable, condition = lambda x: True):     """     Returns the first item in the `iterable` that     satisfies the `condition`.     If the condition is not given, returns the first item of     the iterable.     Raises `StopIteration` if no item satysfing the condition is found.     >>> first( (1,2,3), condition=lambda x: x % 2 == 0)     2     >>> first(range(3, 100))     3     >>> first( () )     Traceback (most recent call last):     ...     StopIteration     """     return next(x for x in iterable if condition(x))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python