Right now I am tracking my index in side the loop like this
index = 0
for entry in longList:
if entry == 'foo':
开发者_StackOverflow社区print index
index += 1
is there a better way to do this?
for index, entry in enumerate(longList):
if entry == 'foo':
print index
Use the enumerate()
built-in function.
for index, entry in enumerate(longList):
if entry == 'foo':
print index
However, in your specific case, you can simply do index = longList.index("foo")
EDIT: If you want to find the indices of multiple matches pretty much as fast as is possible in pure Python, the following code should do the trick:
indices = tuple(index for index, element in enumerate(longList) if element=='foo')
I like list comprehension :)
[index for (index,entry) in enumerate(longList) if entry == 'foo']
Yes, the best way is to do this:
longList.index('foo')
Using enumerate would be a better idea.
for ind,item in enumerate(longList):
if item == 'foo':
print ind
If your list is really long and static, you should consider using a lookup table (actually, a dictionary of index lists with the entry as the key). It will almost pay for itself after the first search, since you currently always iterate over all the elements.
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]'
精彩评论