Python内置函数(18)——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.

Equivalent to:

def enumerate(sequence, start=0):
n = start
for elem in sequence:
yield n, elem
n += 1

说明:

  1. 接受一个可迭代对象(序列或者迭代器),返回一个可枚举对象(同时返回索引和值,其中索引可以指定起始值)。

>>> 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')]
上一篇:android 重启app


下一篇:自定义缓存设计(static缓存数据)