【发布时间】:2011-11-06 05:00:40
【问题描述】:
现在我正在像这样在循环中跟踪我的索引
index = 0
for entry in longList:
if entry == 'foo':
print index
index += 1
有没有更好的方法来做到这一点?
【问题讨论】:
现在我正在像这样在循环中跟踪我的索引
index = 0
for entry in longList:
if entry == 'foo':
print index
index += 1
有没有更好的方法来做到这一点?
【问题讨论】:
for index, entry in enumerate(longList):
if entry == 'foo':
print index
【讨论】:
使用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')
【讨论】:
我喜欢列表理解 :)
[index for (index,entry) in enumerate(longList) if entry == 'foo']
【讨论】:
(index, entry) 周围的括号不是必需的。请记住,在 Python 中,逗号创建元组,而不是括号。此外,通常最好使用生成器表达式而不是列表推导式。所以,(index for index, entry in enumerate(longList) if entry == 'foo').
是的,最好的方法是这样做:
longList.index('foo')
【讨论】:
"foo" 不是 longList 的成员,这将引发 ValueError,而 OP 的代码根本不会打印任何内容。
.index()打了一次电话。因为它是一个 C 函数,所以它肯定比你自己编写的任何 Python 代码都要快。
使用枚举会更好。
for ind,item in enumerate(longList):
if item == 'foo':
print ind
【讨论】:
如果您的列表真的很长而且是静态的,您应该考虑使用查找表(实际上是一个以条目为键的索引列表字典)。在第一次搜索后它几乎可以收回成本,因为您目前总是遍历所有元素。
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]'
【讨论】: