【问题标题】:What is the proper way to track indexes in python?在 python 中跟踪索引的正确方法是什么?
【发布时间】:2011-11-06 05:00:40
【问题描述】:

现在我正在像这样在循环中跟踪我的索引

index = 0
for entry in longList:
    if entry == 'foo':
        print index
    index += 1

有没有更好的方法来做到这一点?

【问题讨论】:

标签: python indexing lookup


【解决方案1】:
for index, entry in enumerate(longList):
    if entry == 'foo':
        print index

【讨论】:

    【解决方案2】:

    使用enumerate() 内置函数。

    for index, entry in enumerate(longList):
        if entry == 'foo':
            print index
    

    但是,在您的具体情况下,您可以简单地使用index = longList.index("foo")

    编辑:如果您想在纯 Python 中尽可能快地找到多个匹配项的索引,以下代码应该可以解决问题:

    indices = tuple(index for index, element in enumerate(longList) if element=='foo')
    

    【讨论】:

      【解决方案3】:

      我喜欢列表理解 :)

      [index for (index,entry) in enumerate(longList) if entry == 'foo']
      

      【讨论】:

      • +1,但(index, entry) 周围的括号不是必需的。请记住,在 Python 中,逗号创建元组,而不是括号。此外,通常最好使用生成器表达式而不是列表推导式。所以,(index for index, entry in enumerate(longList) if entry == 'foo').
      • 带括号对我来说更容易阅读 :) 确实,如果您只想打印,请使用生成器。
      【解决方案4】:

      是的,最好的方法是这样做:

      longList.index('foo')
      

      【讨论】:

      • +1,但是,如果 "foo" 不是 longList 的成员,这将引发 ValueError,而 OP 的代码根本不会打印任何内容。
      • 如果我们变得特别,它不会找到重复的。
      • 我正在这样做,但是当我运行它超过数千个条目时,它会变得越来越慢,我进入列表越深。这就是为什么我使用我现在使用的循环。
      • @johnthexiii:你只给.index()打了一次电话。因为它是一个 C 函数,所以它肯定比你自己编写的任何 Python 代码都要快。
      • 是的,但是如果我有多个匹配“foo”的条目怎么办?那么是不是要执行多次搜索,从而减慢一切?
      【解决方案5】:

      使用枚举会更好。

      for ind,item in enumerate(longList):
          if item == 'foo':
              print ind
      

      【讨论】:

        【解决方案6】:

        如果您的列表真的很长而且是静态的,您应该考虑使用查找表(实际上是一个以条目为键的索引列表字典)。在第一次搜索后它几乎可以收回成本,因为您目前总是遍历所有元素。

        from collections import defaultdict
        
        # Create and fill the table (only once or whenever the list changes)
        lookupTable = defaultdict(list)
        for index, entry in enumerate(longList):
            lookupTable[entry].append(index)
        
        # Search the list (as many times as you want)
        indexes = lookupTable.get('foo')
        # and you get either 'None' or a list of indexes '[1,10,20]'
        

        【讨论】:

        • +1 我可以看到很多应用程序,我必须对此进行一些研究。
        猜你喜欢
        • 2012-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-28
        • 2013-04-05
        相关资源
        最近更新 更多