【问题标题】:Find the index of the second occurrence of a string inside a list查找列表中第二次出现的字符串的索引
【发布时间】:2013-09-03 04:56:27
【问题描述】:

这是我的清单和代码:

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

第一次获取“this”,正常运行,第二次获取,只获取第一个“this”的索引!

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

【问题讨论】:

  • 您到底想做什么?似乎您将单个字符串存储在列表中,这似乎没有必要
  • 实际上,我正在读取一个文件,并将其存储在一个名为 x! 的列表中!我只是举个简单的例子!!
  • 试试看我的回答我想我知道你在做什么
  • 不!情况很复杂!无论如何我得到了答案,谢谢...:)

标签: python string


【解决方案1】:

你可以在这里使用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】:

您可以使用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

【讨论】:

    【解决方案3】:

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

    这个函数会打印出每一行和所有你在文件中每行找到的关键字的索引(如果有的话):

    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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      • 2014-07-15
      • 2013-10-02
      • 2018-11-21
      • 1970-01-01
      • 2021-08-14
      • 2011-02-04
      相关资源
      最近更新 更多