Python标准库-enumerate用法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
以上是关于Python标准库-enumerate用法的主要内容,如果未能解决你的问题,请参考以下文章