Get the first item from an iterable that matches a condition

前端 未结 13 2288
感情败类
感情败类 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 05:05

    The itertools module contains a filter function for iterators. The first element of the filtered iterator can be obtained by calling next() on it:

    from itertools import ifilter
    
    print ifilter((lambda i: i > 3), range(10)).next()
    

提交回复
热议问题