Get the first item from an iterable that matches a condition

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

    Oneliner:

    thefirst = [i for i in range(10) if i > 3][0]
    

    If youre not sure that any element will be valid according to the criteria, you should enclose this with try/except since that [0] can raise an IndexError.

提交回复
热议问题