Find the index of the n'th item in a list

后端 未结 11 1877
余生分开走
余生分开走 2020-12-13 00:04

I want to find the index of the n\'th occurrence of an item in a list. e.g.,

x=[False,True,True,False,True,False,True,False,False,False,True,False,True]
         


        
11条回答
  •  不知归路
    2020-12-13 00:50

    The answer from @Taymon using list.index was great.

    FWIW, here's a functional approach using the itertools module. It works with any iterable input, not just lists:

    >>> from itertools import compress, count, imap, islice
    >>> from functools import partial
    >>> from operator import eq
    
    >>> def nth_item(n, item, iterable):
            indicies = compress(count(), imap(partial(eq, item), iterable))
            return next(islice(indicies, n, None), -1)
    

    The example is nice because it shows off how to effectively combine Python's functional toolset. Note, that once the pipeline is set-up, there are no trips around Python's eval loop -- everything gets done at C speed, with a tiny memory footprint, with lazy evaluation, with no variable assignments, and with separately testable components. IOW, it is everything functional programmers dream about :-)

    Sample run:

    >>> x = [False,True,True,False,True,False,True,False,False,False,True,False,True]
    >>> nth_item(50, True, x)
    -1
    >>> nth_item(0, True, x)
    1
    >>> nth_item(1, True, x)
    2
    >>> nth_item(2, True, x)
    4
    >>> nth_item(3, True, x)
    6
    

提交回复
热议问题