2011-08-29 92 views
11

现在我跟踪我在旁边指数这样在python中跟踪索引的正确方法是什么?

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

循环有没有更好的方式来做到这一点?

+0

你究竟想做什么? –

+1

http://stackoverflow.com/questions/1185545/python-loop-counter-in-a-for-loop/1185557#1185557 – develerx

回答

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

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

longList.index('foo') 
+1

+1,但是,如果'“foo”'isn'会引发'ValueError'是'longList'的成员,而OP的代码将不会打印任何内容。 –

+8

如果我们变得特别,它不会找到重复。 –

+2

我正在这样做,但是当我在数千个条目上运行时,它越来越慢,越深入我进入列表。这就是为什么我正在使用我现在使用的循环。 – John

10

使用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

使用枚举将是一个更好的主意。

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

我喜欢列表理解:)

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

+1,但“(index,entry)”的括号不是必需的。请记住,在Python逗号中创建元组,而不是括号。此外,使用生成器表达式而不是列表理解通常更好。所以,'(索引索引,枚举中的条目(longList)if entry =='foo')'。 –

+1

带圆括号对我来说比较容易阅读:)确实,如果你只想打印,请带上发电机。 – steabert

3

如果你的清单很长,静,你应该考虑使用查找表(实际上,索引列表与项作为重点字典)。在第一次搜索后,它几乎会为自己付出代价,因为你现在总是遍历所有元素。

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]' 
+0

+1我可以看到很多应用程序,我必须对此进行一些研究。 – John

相关问题