Find the index of the second occurrence of a string inside a list

后端 未结 3 1496
耶瑟儿~
耶瑟儿~ 2021-01-20 18:31

This is my list and code:

x=[[\"hi hello\"], [\"this is other\"],[\"this\"],[\"something\"],[\"this\"],[\"last element\"]]
for line in x:
    y=x.index(line)         


        
3条回答
  •  感动是毒
    2021-01-20 19:22

    You can get the second easily enough by using list slices. In the example below, we find the index of the first occurance and then find the index of the first occurance in the sub-list that begins just after the first occurance.

    x=[["hi hello"], ["this is other"],["this"],["something"],["this"],["last element"]]
    for line in x:
        first=x.index(line)
        second=x[first+1:].index(line)
        #code
    

    Bare in mind that using list.index() will return a ValueError if the object isn't in the list. Thus you may want some exception handling around your inner loop.

    So the final code will look somewhat closer to this:

    x=[["hi hello"], ["this is other"],["this"],["something"],["this"],["last element"]]
    for line in x:
        print lines
        try:
            first=x.index(line)
            second=x[first+1:].index(line)
        except:
            first,second=-1,-1
        print first,second
        #code
    

提交回复
热议问题