它可以帮助你了解事物的位置...
l = ['apple', 'banana', 'cabbage']
for idx, item in enumerate(l):
print "the item: %s, is at position %s" % (item, idx)
>>>
the item: apple, is at position 0
the item: banana, is at position 1
the item: cabbage, is at position 2
在以下场景中,这很有帮助。想象一下,你想在列表中查找每个“卷心菜”项目,并知道它们的索引。
l = ['apple', 'banana', 'cabbage', 'monkey', 'kangaroo', 'cabbage']
def find_indexes(lst, match):
results = []
for idx, item in enumerate(l):
if item == match:
results.append(idx)
return results
print find_indexes(l, 'cabbage')
>>>
[2, 5]
int
对象,但是将小值(范围在-5到256之间)进行了内部化。 - Martijn Pietersenumerate
的源代码? - Forethinker