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

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

    if efficiency is a concern i think its better to iterate the normally ( O(N) ) instead of list comprehension which takes O(L) where L is length of list

    Example : Consider a very huge list and you want to find the first occurence N=1 it is obviously better to stop as soon as you find the first occurence

    count = 0
    for index,i in enumerate(L):
        if i:
            count = count + 1
            if count==N:
                return index
    

提交回复
热议问题