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

前端 未结 6 837
傲寒
傲寒 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

    A variation on Alex's answer. This avoids having to type X every time you want to use is_odd or whichever predicate

    >>> class X(object):
    ...     def __init__(self, pred): self.pred = pred
    ...     def __eq__(self, other): return self.pred(other)
    ... 
    >>> L = [8,10,4,5,7]
    >>> is_odd = X(lambda x: x%2 != 0)
    >>> L.index(is_odd)
    3
    >>> less_than_six = X(lambda x: x<6)
    >>> L.index(less_than_six)
    2
    

提交回复
热议问题