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

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

    Here is another way to find the nth occurrence of x in a list itrbl:

    def nthoccur(nth,x,itrbl):
        count,index = 0,0
        while count < nth:
            if index > len(itrbl) - 1:
                return None
            elif itrbl[index] == x:
                count += 1
                index += 1
            else:
                index += 1
        return index - 1
    

提交回复
热议问题