4

这是我的清单和代码:

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

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

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

4

3 回答 3

5

你可以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']
于 2013-09-03T05:06:36.000 回答
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

请记住,如果对象不在列表中, usinglist.index()将返回 a 。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
于 2013-09-03T04:58:39.567 回答
1

如果获取关键字的索引是您唯一需要做的事情,则无需将字符串存储在列表中(即使这只是您想到的示例!)。

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

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 
于 2013-09-03T05:34:10.643 回答