Get the first item from an iterable that matches a condition

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

    By using

    (index for index, value in enumerate(the_iterable) if condition(value))
    

    one can check the condition of the value of the first item in the_iterable, and obtain its index without the need to evaluate all of the items in the_iterable.

    The complete expression to use is

    first_index = next(index for index, value in enumerate(the_iterable) if condition(value))
    

    Here first_index assumes the value of the first value identified in the expression discussed above.

提交回复
热议问题