Get the first item from an iterable that matches a condition

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

    Similar to using ifilter, you could use a generator expression:

    >>> (x for x in xrange(10) if x > 5).next()
    6
    

    In either case, you probably want to catch StopIteration though, in case no elements satisfy your condition.

    Technically speaking, I suppose you could do something like this:

    >>> foo = None
    >>> for foo in (x for x in xrange(10) if x > 5): break
    ... 
    >>> foo
    6
    

    It would avoid having to make a try/except block. But that seems kind of obscure and abusive to the syntax.

提交回复
热议问题