Python: return the index of the first element of a list which makes a passed function true

前端 未结 6 843
傲寒
傲寒 2020-11-29 04:37

The list.index(x) function returns the index in the list of the first item whose value is x.

Is there a function, list_func_index()

6条回答
  •  孤城傲影
    2020-11-29 04:53

    You could do that in a one-liner using generators:

    next(i for i,v in enumerate(l) if is_odd(v))
    

    The nice thing about generators is that they only compute up to the requested amount. So requesting the first two indices is (almost) just as easy:

    y = (i for i,v in enumerate(l) if is_odd(v))
    x1 = next(y)
    x2 = next(y)
    

    Though, expect a StopIteration exception after the last index (that is how generators work). This is also convenient in your "take-first" approach, to know that no such value was found --- the list.index() function would throw ValueError here.

提交回复
热议问题