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

前端 未结 6 845
傲寒
傲寒 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 05:03

    Not one single function, but you can do it pretty easily:

    >>> test = lambda c: c == 'x'
    >>> data = ['a', 'b', 'c', 'x', 'y', 'z', 'x']
    >>> map(test, data).index(True)
    3
    >>>
    

    If you don't want to evaluate the entire list at once you can use itertools, but it's not as pretty:

    >>> from itertools import imap, ifilter
    >>> from operator import itemgetter
    >>> test = lambda c: c == 'x'
    >>> data = ['a', 'b', 'c', 'x', 'y', 'z']
    >>> ifilter(itemgetter(1), enumerate(imap(test, data))).next()[0]
    3
    >>> 
    

    Just using a generator expression is probably more readable than itertools though.

    Note in Python3, map and filter return lazy iterators and you can just use:

    from operator import itemgetter
    test = lambda c: c == 'x'
    data = ['a', 'b', 'c', 'x', 'y', 'z']
    next(filter(itemgetter(1), enumerate(map(test, data))))[0]  # 3
    

提交回复
热议问题