enumerate用法
方法解读:enumerate(iterable, start=0)
Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.
返回枚举对象。iterable必须是序列、迭代器或其他支持迭代的对象。枚举 () 返回的迭代器的 _ _ next _ _() 方法返回一个元组,其中包含一个计数 (从start开始,默认为0) 和通过迭代获得的值。
seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
Equivalent to:def enumerate(sequence, start=0):
n = start
for elem in sequence:
yield n, elem
n += 1
案例
>>> a
['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
print(i,a[i])
0 Mary
1 had
2 a
3 little
4 lamb
>>> list(enumerate(a,start=0))
[(0, 'Mary'), (1, 'had'), (2, 'a'), (3, 'little'), (4, 'lamb')]
心有猛虎,当细嗅蔷薇
浙公网安备 33010602011771号