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

时间:2013-09-03 04:56:27

标签: python string

这是我的清单和代码:

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

第一次获得“this”,它可以正常工作,但是第二次,它只获得第一个“this”的索引!

如何在列表中找到第二次出现的字符串?

3 个答案:

答案 0 :(得分:4)

使用list slices可以轻松获得第二个。在下面的例子中,我们找到第一次出现的索引,然后找到在第一次出现之后开始的子列表中第一次出现的索引。

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

请注意,如果对象不在列表中,则使用list.index()将返回ValueError。因此,您可能需要围绕内循环进行一些异常处理。

所以最终的代码看起来会更接近这个:

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

答案 1 :(得分:4)

您可以在此处使用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']

答案 2 :(得分:1)

如果只需要获取关键字的索引,那么就不需要在列表中存储字符串(即使这只是你想到的一个例子!)。

此函数将打印出每一行, all 您在文件中每行找到的关键字索引(如果有):

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”和第1 /第2次出现。 例如,假设您的文件如下所示:

hello this
this is cool
hello there
this this this

然后该功能将如下工作:

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