Python中的“iterable”、“iterator”和“iteration”是什么?它们是如何定义的?
当前回答
我不知道这是否对任何人都有帮助,但我总是喜欢在脑子里把概念形象化,以便更好地理解它们。所以,就像我有一个小儿子一样,我用砖块和白纸来想象迭代器/迭代器的概念。
Suppose we are in the dark room and on the floor we have bricks for my son. Bricks of different size, color, does not matter now. Suppose we have 5 bricks like those. Those 5 bricks can be described as an object – let’s say bricks kit. We can do many things with this bricks kit – can take one and then take second and then third, can change places of bricks, put first brick above the second. We can do many sorts of things with those. Therefore this bricks kit is an iterable object or sequence as we can go through each brick and do something with it. We can only do it like my little son – we can play with one brick at a time. So again I imagine myself this bricks kit to be an iterable.
现在请记住,我们是在一个黑暗的房间里。或者几乎是黑暗的。问题是我们看不清这些砖,它们是什么颜色,什么形状等等。所以即使我们想对它们做些什么——也就是迭代它们——我们也不知道要做什么,怎么做,因为太暗了。
我们能做的是靠近第一块砖-作为一个砖套件的元素-我们可以放一张白色荧光纸,以便我们看到第一块砖元素在哪里。每次我们从工具箱中取出一块砖,我们就把这张白纸换成下一块砖,这样就能在黑暗的房间里看到它。这张白纸只不过是一个迭代器。它也是一个对象。而是一个我们可以使用可迭代对象中的元素的对象——bricks工具包。
顺便说一下,这解释了我早期的错误,当我在IDLE中尝试以下操作时,得到了一个TypeError:
>>> X = [1,2,3,4,5]
>>> next(X)
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
next(X)
TypeError: 'list' object is not an iterator
这里的列表X是我们的砖块工具包,但不是一张白纸。我需要先找到一个迭代器:
>>> X = [1,2,3,4,5]
>>> bricks_kit = [1,2,3,4,5]
>>> white_piece_of_paper = iter(bricks_kit)
>>> next(white_piece_of_paper)
1
>>> next(white_piece_of_paper)
2
>>>
不知道有没有帮助,但对我有帮助。如果有人能确认/纠正这个概念的可视化,我会很感激。这会帮助我了解更多。
其他回答
我不知道这是否对任何人都有帮助,但我总是喜欢在脑子里把概念形象化,以便更好地理解它们。所以,就像我有一个小儿子一样,我用砖块和白纸来想象迭代器/迭代器的概念。
Suppose we are in the dark room and on the floor we have bricks for my son. Bricks of different size, color, does not matter now. Suppose we have 5 bricks like those. Those 5 bricks can be described as an object – let’s say bricks kit. We can do many things with this bricks kit – can take one and then take second and then third, can change places of bricks, put first brick above the second. We can do many sorts of things with those. Therefore this bricks kit is an iterable object or sequence as we can go through each brick and do something with it. We can only do it like my little son – we can play with one brick at a time. So again I imagine myself this bricks kit to be an iterable.
现在请记住,我们是在一个黑暗的房间里。或者几乎是黑暗的。问题是我们看不清这些砖,它们是什么颜色,什么形状等等。所以即使我们想对它们做些什么——也就是迭代它们——我们也不知道要做什么,怎么做,因为太暗了。
我们能做的是靠近第一块砖-作为一个砖套件的元素-我们可以放一张白色荧光纸,以便我们看到第一块砖元素在哪里。每次我们从工具箱中取出一块砖,我们就把这张白纸换成下一块砖,这样就能在黑暗的房间里看到它。这张白纸只不过是一个迭代器。它也是一个对象。而是一个我们可以使用可迭代对象中的元素的对象——bricks工具包。
顺便说一下,这解释了我早期的错误,当我在IDLE中尝试以下操作时,得到了一个TypeError:
>>> X = [1,2,3,4,5]
>>> next(X)
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
next(X)
TypeError: 'list' object is not an iterator
这里的列表X是我们的砖块工具包,但不是一张白纸。我需要先找到一个迭代器:
>>> X = [1,2,3,4,5]
>>> bricks_kit = [1,2,3,4,5]
>>> white_piece_of_paper = iter(bricks_kit)
>>> next(white_piece_of_paper)
1
>>> next(white_piece_of_paper)
2
>>>
不知道有没有帮助,但对我有帮助。如果有人能确认/纠正这个概念的可视化,我会很感激。这会帮助我了解更多。
迭代是一个通用术语,指一个接一个地获取某物的每一项。任何时候使用循环,显式或隐式,遍历一组项,这就是迭代。
在Python中,iterable和iterator有特定的含义。
iterable是一个具有__iter__方法的对象,该方法返回一个迭代器,或者定义了__getitem__方法,该方法可以接受从0开始的顺序索引(并在索引不再有效时引发IndexError)。iterable是一个你可以从中获取迭代器的对象。
迭代器是具有next (Python 2)或__next__ (Python 3)方法的对象。
无论何时在Python中使用for循环、map或列表推导式等,都会自动调用下一个方法从迭代器中获取每一项,从而完成迭代过程。
开始学习的一个好地方是教程的迭代器部分和标准类型页面的迭代器类型部分。在您理解了基础知识之后,请尝试函数式编程HOWTO中的迭代器部分。
下面是我的小抄:
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()方法的对象,该方法返回一个迭代器。这是可以循环的。 示例:列表是可迭代的,因为我们可以遍历列表BUT不是迭代器 迭代器是一个可以从中获取迭代器的对象。它是一个具有状态的对象,以便在迭代过程中记住它所处的位置
要查看对象是否有iter()方法,可以使用下面的函数。
ls = ['hello','bye']
print(dir(ls))
输出
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
正如你所看到的有iter(),这意味着它是一个可迭代对象,但不包含next()方法,这是迭代器对象的一个特征
无论何时在Python中使用for循环或map或列表推导式,都会自动调用next方法以从迭代中获取每一项
其他人已经全面地解释了什么是iterable和iterator,所以我将尝试对生成器做同样的事情。
恕我直言,理解生成器的主要问题是“生成器”这个词的混淆用法,因为这个词有两种不同的含义:
作为创建(生成)迭代器的工具, 以返回迭代器的函数形式(即在函数体中包含yield语句), 以生成器表达式的形式 作为使用该工具的结果,即结果迭代器。 (在这个意思中,生成器是迭代器的一种特殊形式——“generator”这个词指出了这个迭代器是如何创建的。)
Generator作为第一种工具:
In[2]: def my_generator():
...: yield 100
...: yield 200
In[3]: my_generator
输出[3]:<function __main__.my_generator()> .my_generator(
In[4]: type(my_generator)
[4]:函数
生成器作为使用此工具的结果(即迭代器):
In[5]: my_iterator = my_generator()
In[6]: my_iterator
输出[6]:<生成器对象my_generator at 0x00000000053EAE48>
In[7]: type(my_iterator)
[7]:发电机
Generator作为第二种类型的工具-与该工具的结果迭代器难以区分:
In[8]: my_gen_expression = (2 * i for i in (10, 20))
In[9]: my_gen_expression
Out[9]: <generator object <genexpr> at 0x000000000542C048>
In[10]: type(my_gen_expression)
[10]:发电机