简体   繁体   中英

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

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)
    #code

The first time it gets "this", it works properly, but for the second time, it gets the index of the first "this" only!

How can I find the second occurrence of a string inside a list?

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

You could use enumerate(...) here.

>>> x=[["hi hello"], ["this is other"],["this"],["something"],["this"],["last element"]]
>>> for index, line in enumerate(x):
        print index, line


0 ['hi hello']
1 ['this is other']
2 ['this']
3 ['something']
4 ['this']
5 ['last element']

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM