Get the first item from an iterable that matches a condition

前端 未结 13 2303
感情败类
感情败类 2020-11-22 04:43

I would like to get the first item from a list matching a condition. It\'s important that the resulting method not process the entire list, which could be quite large. For e

13条回答
  •  臣服心动
    2020-11-22 04:56

    The most efficient way in Python 3 are one of the following (using a similar example):

    With "comprehension" style:

    next(i for i in range(100000000) if i == 1000)
    

    WARNING: The expression works also with Python 2, but in the example is used range that returns an iterable object in Python 3 instead of a list like Python 2 (if you want to construct an iterable in Python 2 use xrange instead).

    Note that the expression avoid to construct a list in the comprehension expression next([i for ...]), that would cause to create a list with all the elements before filter the elements, and would cause to process the entire options, instead of stop the iteration once i == 1000.

    With "functional" style:

    next(filter(lambda i: i == 1000, range(100000000)))
    

    WARNING: This doesn't work in Python 2, even replacing range with xrange due that filter create a list instead of a iterator (inefficient), and the next function only works with iterators.

    Default value

    As mentioned in other responses, you must add a extra-parameter to the function next if you want to avoid an exception raised when the condition is not fulfilled.

    "functional" style:

    next(filter(lambda i: i == 1000, range(100000000)), False)
    

    "comprehension" style:

    With this style you need to surround the comprehension expression with () to avoid a SyntaxError: Generator expression must be parenthesized if not sole argument:

    next((i for i in range(100000000) if i == 1000), False)
    

提交回复
热议问题