Get the first item from an iterable that matches a condition

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

    This question already has great answers. I'm only adding my two cents because I landed here trying to find a solution to my own problem, which is very similar to the OP.

    If you want to find the INDEX of the first item matching a criteria using generators, you can simply do:

    next(index for index, value in enumerate(iterable) if condition)
    

提交回复
热议问题