Python标准库-enumerate用法
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.
将一个可支持迭代的对象,转化为枚举, 所以列表,序列,或者其他可迭代的对象即可以;枚举会返回一个包含数字和迭代器中的值的元组;最终返回一个可枚举对象;
典型用法:
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
简单实现:
def enumerate(sequence, start=0): n = start for x in sequence: yield n, x n += 1