現在我跟蹤我在旁邊指數這樣在python中跟蹤索引的正確方法是什麼?
index = 0
for entry in longList:
if entry == 'foo':
print index
index += 1
循環有沒有更好的方式來做到這一點?
現在我跟蹤我在旁邊指數這樣在python中跟蹤索引的正確方法是什麼?
index = 0
for entry in longList:
if entry == 'foo':
print index
index += 1
循環有沒有更好的方式來做到這一點?
for index, entry in enumerate(longList):
if entry == 'foo':
print index
是,最好的辦法是做這樣的:
longList.index('foo')
+1,但是,如果'「foo」'isn'會引發'ValueError'是'longList'的成員,而OP的代碼將不會打印任何內容。 –
如果我們變得特別,它不會找到重複。 –
我正在這樣做,但是當我在數千個條目上運行時,它越來越慢,越深入我進入列表。這就是爲什麼我正在使用我現在使用的循環。 – John
使用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')
使用枚舉將是一個更好的主意。
for ind,item in enumerate(longList):
if item == 'foo':
print ind
我喜歡列表理解:)
[index for (index,entry) in enumerate(longList) if entry == 'foo']
+1,但「(index,entry)」的括號不是必需的。請記住,在Python逗號中創建元組,而不是括號。此外,使用生成器表達式而不是列表理解通常更好。所以,'(索引索引,枚舉中的條目(longList)if entry =='foo')'。 –
帶圓括號對我來說比較容易閱讀:)確實,如果你只想打印,請帶上發電機。 – steabert
如果你的清單很長,靜,你應該考慮使用查找表(實際上,索引列表與項作爲重點字典)。在第一次搜索後,它幾乎會爲自己付出代價,因爲你現在總是遍歷所有元素。
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我可以看到很多應用程序,我必須對此進行一些研究。 – John
你究竟想做什麼? –
http://stackoverflow.com/questions/1185545/python-loop-counter-in-a-for-loop/1185557#1185557 – develerx