Get the first item from an iterable that matches a condition

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

    Damn Exceptions!

    I love this answer. However, since next() raise a StopIteration exception when there are no items, i would use the following snippet to avoid an exception:

    a = []
    item = next((x for x in a), None)
    

    For example,

    a = []
    item = next(x for x in a)
    

    Will raise a StopIteration exception;

    Traceback (most recent call last):
      File "", line 1, in 
    StopIteration
    

提交回复
热议问题