迭代器和枚举器对象的区别

3

enumerate()函数接收一个迭代器并返回一个枚举对象。这个对象可以像迭代器一样使用,在每次迭代时,它都会返回一个2元组,其中第一项是迭代编号(默认从0开始),第二项是调用enumerate()时传入的迭代器中的下一项。

引自《Programming in Python 3 A Complete Introduction to the Python Language》。

我是Python的新手,并不真正理解上述文字的含义。然而,从我对示例代码的理解来看,enumerator对象返回一个包含迭代器索引号和值的2元组。我对吗?

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


1
请参阅 https://dev59.com/32kw5IYBdhLWcg3wdKMv 了解 Python 中被认为是迭代器的内容,以及 https://dev59.com/L2Eh5IYBdhLWcg3wpE7w 了解枚举的一些信息。 - Thierry Lathuille
请说明您对“迭代器”和“枚举器”的理解。根据您目前的知识水平,我们需要包含这个讨论。在Stack Overflow上,我们避免重复其他网站已经包含的信息。 - Prune
1个回答

4
你对其最终功能的理解是正确的,但该引用的措辞是误导性的。一个“enumerator”(不是真正的标准术语)和一个迭代器之间没有区别,或者更确切地说,“enumerator”是一种迭代器。`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____next__

>>> 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参数,并且传递的迭代器不一定是可索引的:

>>> 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)]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接