Python中的“iterable”、“iterator”和“iteration”是什么?它们是如何定义的?


当前回答

下面是我的小抄:

 sequence
  +
  |
  v
   def __getitem__(self, index: int):
  +    ...
  |    raise IndexError
  |
  |
  |              def __iter__(self):
  |             +     ...
  |             |     return <iterator>
  |             |
  |             |
  +--> or <-----+        def __next__(self):
       +        |       +    ...
       |        |       |    raise StopIteration
       v        |       |
    iterable    |       |
           +    |       |
           |    |       v
           |    +----> and +-------> iterator
           |                               ^
           v                               |
   iter(<iterable>) +----------------------+
                                           |
   def generator():                        |
  +    yield 1                             |
  |                 generator_expression +-+
  |                                        |
  +-> generator() +-> generator_iterator +-+

小测验:你看到…

每个迭代器都是可迭代对象? 容器对象的__iter__()方法可以实现为生成器? 具有__next__方法的迭代器不一定是迭代器?

答案:

Every iterator must have an __iter__ method. Having __iter__ is enough to be an iterable. Therefore every iterator is an iterable. When __iter__ is called it should return an iterator (return <iterator> in the diagram above). Calling a generator returns a generator iterator which is a type of iterator. class Iterable1: def __iter__(self): # a method (which is a function defined inside a class body) # calling iter() converts iterable (tuple) to iterator return iter((1,2,3)) class Iterable2: def __iter__(self): # a generator for i in (1, 2, 3): yield i class Iterable3: def __iter__(self): # with PEP 380 syntax yield from (1, 2, 3) # passes assert list(Iterable1()) == list(Iterable2()) == list(Iterable3()) == [1, 2, 3] Here is an example: class MyIterable: def __init__(self): self.n = 0 def __getitem__(self, index: int): return (1, 2, 3)[index] def __next__(self): n = self.n = self.n + 1 if n > 3: raise StopIteration return n # if you can iter it without raising a TypeError, then it's an iterable. iter(MyIterable()) # but obviously `MyIterable()` is not an iterator since it does not have # an `__iter__` method. from collections.abc import Iterator assert isinstance(MyIterable(), Iterator) # AssertionError

其他回答

iterable是一个具有__iter__()方法的对象。它可以迭代多次,比如list()和tuple()。

迭代器是进行迭代的对象。它由__iter__()方法返回,通过自己的__iter__()方法返回自身,并有一个next()方法(3.x中的__next__())。

迭代是调用next()响应的过程。__next__()直到引发StopIteration。

例子:

>>> a = [1, 2, 3] # iterable
>>> b1 = iter(a) # iterator 1
>>> b2 = iter(a) # iterator 2, independent of b1
>>> next(b1)
1
>>> next(b1)
2
>>> next(b2) # start over, as it is the first call to b2
1
>>> next(b1)
3
>>> next(b1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> b1 = iter(a) # new one, start over
>>> next(b1)
1

我不认为你能得到比文档更简单的东西,但我会尝试:

Iterable是可以被迭代的对象。在实践中,它通常是指一个序列,例如,有开始和结束的东西,以及一些贯穿其中所有项目的方法。 您可以将Iterator视为一个辅助伪方法(或伪属性),它给出(或保存)可迭代对象中的下一个(或第一个)项。(实际上它只是一个定义next()方法的对象) 《韦氏词典》对迭代这个词的定义可能是最好的解释:

B:重复指定的计算机指令序列 次数或直到满足条件-比较递归

在处理可迭代对象和迭代器之前,决定可迭代对象和迭代器的主要因素是序列

序列:序列是数据的集合

Iterable: Iterable是支持__iter__方法的序列类型对象。

Iter方法:Iter方法以序列为输入,创建一个对象,称为迭代器

迭代器:迭代器是调用next方法和横向遍历序列的对象。在调用下一个方法时,它返回当前遍历的对象。

例子:

x=[1,2,3,4]

X是一个由数据集合组成的序列

y=iter(x)

在调用iter(x)时,只有当x对象有iter方法时,它才会返回一个迭代器,否则会引发异常。如果返回迭代器,则y的赋值如下:

y=[1,2,3,4]

因为y是一个迭代器,所以它支持next()方法

在调用next方法时,它逐个返回列表中的各个元素。

返回序列的最后一个元素后,如果再次调用下一个方法,将引发StopIteration错误

例子:

>>> y.next()
1
>>> y.next()
2
>>> y.next()
3
>>> y.next()
4
>>> y.next()
StopIteration

迭代是一个通用术语,指一个接一个地获取某物的每一项。任何时候使用循环,显式或隐式,遍历一组项,这就是迭代。

在Python中,iterable和iterator有特定的含义。

iterable是一个具有__iter__方法的对象,该方法返回一个迭代器,或者定义了__getitem__方法,该方法可以接受从0开始的顺序索引(并在索引不再有效时引发IndexError)。iterable是一个你可以从中获取迭代器的对象。

迭代器是具有next (Python 2)或__next__ (Python 3)方法的对象。

无论何时在Python中使用for循环、map或列表推导式等,都会自动调用下一个方法从迭代器中获取每一项,从而完成迭代过程。

开始学习的一个好地方是教程的迭代器部分和标准类型页面的迭代器类型部分。在您理解了基础知识之后,请尝试函数式编程HOWTO中的迭代器部分。

以下是我在教授Python课程时使用的解释:

ITERABLE是:

任何可以循环的东西(例如,你可以循环一个字符串或文件)或 任何可以出现在for循环右边的东西:for x in iterable:…或 任何你可以用iter()调用并返回ITERATOR: iter(obj)或 一个定义__iter__的对象,该对象返回一个新的ITERATOR, 或者它可能有一个适合索引查找的__getitem__方法。

ITERATOR是一个对象:

在迭代过程中,state会记住它的位置, 使用__next__方法: 返回迭代中的下一个值 更新状态以指向下一个值 信号,当它完成时,引发StopIteration 并且它是可自迭代的(意味着它有一个返回self的__iter__方法)。

注:

Python 3中的__next__方法在Python 2中拼写为next,并且 内置函数next()在传递给它的对象上调用该方法。

例如:

>>> s = 'cat'      # s is an ITERABLE
                   # s is a str object that is immutable
                   # s has no state
                   # s has a __getitem__() method 

>>> t = iter(s)    # t is an ITERATOR
                   # t has state (it starts by pointing at the "c"
                   # t has a next() method and an __iter__() method

>>> next(t)        # the next() function returns the next value and advances the state
'c'
>>> next(t)        # the next() function returns the next value and advances
'a'
>>> next(t)        # the next() function returns the next value and advances
't'
>>> next(t)        # next() raises StopIteration to signal that iteration is complete
Traceback (most recent call last):
...
StopIteration

>>> iter(t) is t   # the iterator is self-iterable