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

后端 未结 3 1448
耶瑟儿~
耶瑟儿~ 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:28

    If getting the indices of the keyword is the only thing you need to do, then storing strings in a list is unnecessary (even if this was just an example you thought of!).

    This function would print out each line and all the indices of the keyword (if any) that you give found per line in the file:

    def getIndices(keyword):
    
        f = open('pathToYourFile', 'r')
        for line in f:
    
            wordList = line.split()
            buf = line.strip("\n") + ": "
    
            i = 0
            while i < len(wordList):
                if wordList[i] == keyword:
                    buf += str(i) + " "
                i += 1
    
            print buf
    

    This way you won't be limited to the keyword "this" and 1st/2nd occurrences. For example, let's say your file looked like this:

    hello this
    this is cool
    hello there
    this this this
    

    Then the function will work like this:

    >>> getIndices("this")
    hello this: 1 
    this is cool: 0 
    hello there: 
    this this this: 0 1 2 
    

提交回复
热议问题