简体   繁体   English

查找列表中字符串第二次出现的索引

[英]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! 第一次获得“ this”,它可以正常工作,但是第二次,它仅获得第一个“ this”的索引!

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. 切记,如果对象不在列表中,则使用list.index()将返回ValueError 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. 您可以在此处使用enumerate(...)

>>> 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. 这样,您将不仅限于关键字“ this”和第1/2次出现。 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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Python 3 中查找字符串中第二次出现的短语的索引? - How to find index of second occurrence of a phrase in a string in Python 3? Python:找到第一个x的索引,然后找到第二个x的索引 - Python: Find index of the first occurrence of x and then the index of the second occurrence of x Python - 查找字符串中第一次出现的字符串列表的索引位置 - Python - find index position of first occurrence of a list of strings within a string 在排序列表中查找首次出现的索引 - Find index of first occurrence in sorted list 查找列表中最后一次出现唯一值的索引 - Find index of last occurrence of unique value in a list 查找字符串中子字符串最后一次出现的索引 - Find index of last occurrence of a substring in a string 在列表列表中查找字符串的出现次数 - Find the number of occurrence of a string in a list of list 如何将字符串从第一次出现的子字符串的索引切片到Python中第二次出现的子字符串? - How can I slice a string from the index of the first occurrence of a sub string to the second occurrence of a sub string in Python? 在带引号的文件中查找字符串中第二次出现的字符串,并返回该字符串的名称 - Find the second occurrence of string in a file with quoted text and return name of that String 列表:查找第一个索引并计算列表列表中特定列表的出现次数 - List: Find the first index and count the occurrence of a specific list in list of lists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM