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

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

    I think this should work.

    def get_nth_occurrence_of_specific_term(my_list, term, n):
        assert type(n) is int and n > 0
        start = -1
        for i in range(n):
            if term not in my_list[start + 1:]:
                return -1
            start = my_list.index(term, start + 1)
        return start
    

提交回复
热议问题