您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

enumerate()是否产生一个生成器对象?

enumerate()是否产生一个生成器对象?

虽然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中,生成器基本上是一种特定类型的迭代器,通过使用ayield函数返回数据来实现。但是,enumerate实际上是用C而不是纯Python实现的,因此没有yield涉及。您可以在此处找到源:http ://hg.python.org/cpython/file/2.7/Objects/enumobject.c

其他 2022/1/1 18:37:35 有469人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶