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

后端 未结 11 1886
余生分开走
余生分开走 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:41

    A solution that first creates a list object and returns the nth-1 element of this list : function occurence()

    And a solution that fulfill functional programmers'dreams too, I think, using generators, because I love them : function occur()

    S = 'stackoverflow.com is a fantastic amazing site'
    print 'object S is string %r' % S
    print "indexes of 'a' in S :",[indx for indx,elem in enumerate(S) if elem=='a']
    
    def occurence(itrbl,x,nth):
        return [indx for indx,elem in enumerate(itrbl)
                if elem==x ][nth-1] if x in itrbl \
               else None
    
    def occur(itrbl,x,nth):
        return (i for pos,i in enumerate(indx for indx,elem in enumerate(itrbl)
                                         if elem==x)
                if pos==nth-1).next() if x in itrbl\
                else   None
    
    print "\noccurence(S,'a',4th) ==",occurence(S,'a',4)
    print "\noccur(S,'a',4th) ==",occur(S,'a',4)
    

    result

    object S is string 'stackoverflow.com is a fantastic amazing site'
    indexes of 'a' in S : [2, 21, 24, 27, 33, 35]
    
    occur(S,'a',4th) == 27
    
    occurence(S,'a',4th) == 27
    

    The second solution seems complex but it isn't really. It doesn't need to run completely through the iterable: the process stops as soon as the wanted occurence is found.

提交回复
热议问题