【问题标题】:Difference between Iterator and Enumerator object迭代器和枚举器对象之间的区别
【发布时间】:2020-04-11 05:32:06
【问题描述】:

enumerate() 函数接受一个迭代器并返回一个枚举器对象。这个对象可以被视为一个迭代器,在每次迭代时它返回一个 2 元组,元组的第一项是迭代号(默认从 0 开始),第二项是迭代器中的下一项 enumerate() 被调用在。

引用自“Python 3 中的编程:Python 语言的完整介绍。

我是 Python 新手,从上面的文字中并不真正理解它的含义。但是,根据我对示例代码的理解,枚举器对象返回一个带有索引号和迭代器值的 2 元组。我说的对吗?

迭代器和枚举器有什么区别?

【问题讨论】:

标签: python python-3.x iterator enumerator


【解决方案1】:

您对其最终作用的理解是正确的,但该引文中的措辞具有误导性。 “枚举器”(不是真正的标准术语)和迭代器之间没有区别,或者更确切地说,“枚举器”是一种 迭代器。 enumerate 返回一个enumerate 对象,所以enumerate一个类

>>> enumerate
<class 'enumerate'>
>>> type(enumerate)
<class 'type'>
>>> enumerate(())
<enumerate object at 0x10ad9c300>

就像其他内置类型一样list

>>> list
<class 'list'>
>>> type(list)
<class 'type'>
>>> type([1,2,3]) is list
True

或自定义类型:

>>> class Foo:
...     pass
...
>>> Foo
<class '__main__.Foo'>
<class 'type'>
>>> type(Foo())
<class '__main__.Foo'>
>>>

enumerate 对象是迭代器。并不是说它们可以被“视为类似”的迭代器,它们是迭代器,迭代器是满足以下条件的任何类型:它们定义了__iter__ 和@987654330 @:

>>> en = enumerate([1])
>>> en.__iter__
<method-wrapper '__iter__' of enumerate object at 0x10ad9c440>
>>> en.__next__
<method-wrapper '__next__' of enumerate object at 0x10ad9c440>

还有iter(iterator) is iterator:

>>> iter(en) is en
True
>>> en
<enumerate object at 0x10ad9c440>
>>> iter(en)
<enumerate object at 0x10ad9c440>

见:

>>> next(en)
(0, 1)

现在,具体来说,它不返回索引值本身,而是返回一个二元组,其中包含传入的迭代中的下一个值以及单调递增的整数,默认从0开始,但可以带start参数,传入的iterable不必是可索引的:

>>> class Iterable:
...     def __iter__(self):
...         yield 1
...         yield 2
...         yield 3
...
>>> iterable = Iterable()
>>> iterable[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'Iterable' object is not subscriptable
>>> list(enumerate(iterable))
[(0, 1), (1, 2), (2, 3)]
>>> list(enumerate(iterable, start=1))
[(1, 1), (2, 2), (3, 3)]
>>> list(enumerate(iterable, start=17))
[(17, 1), (18, 2), (19, 3)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-31
    • 2013-10-27
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    相关资源
    最近更新 更多