虽然Python文档说这
enumerate在功能上等同于:
def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1
实
enumerate函数返回 迭代器 ,但不返回实际生成器。
help(x)创建
enumerate对象后调用可以看到以下内容:
>>> x = enumerate([1,2])>>> help(x)class enumerate(object) | enumerate(iterable[, start]) -> iterator for index, value of iterable | | Return an enumerate object. iterable must be another object that supports | iteration. The enumerate object yields pairs containing a count (from | start, which defaults to zero) and a value yielded by the iterable argument. | enumerate is useful for obtaining an indexed list: | (0, seq[0]), (1, seq[1]), (2, seq[2]), ... | | Methods defined here: | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __iter__(...) | x.__iter__() <==> iter(x) | | next(...) | x.next() -> the next value, or raise StopIteration | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T在Python中,生成器基本上是一种特定类型的迭代器,通过使用a
yield从函数返回数据来实现。但是,
enumerate实际上是用C而不是纯Python实现的,因此没有
yield涉及。您可以在此处找到源:http
:
//hg.python.org/cpython/file/2.7/Objects/enumobject.c



