Python中的“iterable”、“iterator”和“iteration”是什么?它们是如何定义的?
当前回答
迭代对象有一个__iter__方法,每次都会实例化一个新的迭代器。 迭代器实现了一个__next__方法返回单个项,以及一个__iter__方法返回self。 因此,迭代器也是可迭代的,但可迭代的不是迭代器。
卢西亚诺·拉马略,流利的蟒蛇。
其他回答
上面的答案很好,但就我所见,对像我这样的人来说,没有足够的区别。
此外,人们倾向于把“X是一个具有__foo__()方法的对象”这样的定义放在前面,从而变得“过于python化”。这样的定义是正确的——它们基于duck-typing哲学,但是在试图理解概念的简单性时,对方法的关注往往会变得偏颇。
所以我添加了我的版本。
在自然语言中,
迭代是在一行元素中每次取一个元素的过程。
在Python中,
Iterable是一个对象,它是可迭代的,简单地说 它可以在迭代中使用,例如使用for循环。如何?通过使用迭代器。 我将在下面解释。 ... 而iterator是一个对象,它定义了如何实际执行 迭代——特别是下一个元素是什么。这就是为什么它一定是 next()方法。
迭代器本身也是可迭代的,区别在于它们的__iter__()方法返回相同的对象(self),而不管它的项是否已被之前对next()的调用所消耗。
那么,当Python解释器在obj: statement中看到for x时,它会怎么想?
看,一个for循环。看起来像是迭代器的工作…让我们买一个. ... 这里有个obj,我们来问他。 " obj先生,你有迭代器吗"(…调用iter(obj),它调用 Obj.__iter__(),它愉快地分发了一个闪亮的新迭代器_i。) 好吧,这很简单……让我们开始迭代。(x = _i.next()…X = _i.next()…
因为Mr. obj在这个测试中成功了(通过让某个方法返回一个有效的迭代器),我们用一个形容词来奖励他:你现在可以称他为“可迭代的Mr. obj”。
然而,在简单的情况下,将迭代器和iterable分开使用通常没有什么好处。所以你只定义了一个对象,它也是它自己的迭代器。(Python并不真正关心obj传递的_i是不是那么闪亮,而只是obj本身。)
这就是为什么在我看到的大多数例子中(也是让我一次又一次困惑的例子), 你可以看到:
class IterableExample(object):
def __iter__(self):
return self
def next(self):
pass
而不是
class Iterator(object):
def next(self):
pass
class Iterable(object):
def __iter__(self):
return Iterator()
不过,在有些情况下,将迭代器与可迭代对象分开可以带来好处,比如当你想要有一行项,但有更多的“游标”时。例如,当您想要处理“当前”和“即将”元素时,可以为这两个元素使用单独的迭代器。或者从一个巨大的列表中抽取多个线程:每个线程都有自己的迭代器来遍历所有项。请看上面@Raymond和@glglgl的回答。
想象一下你能做什么:
class SmartIterableExample(object):
def create_iterator(self):
# An amazingly powerful yet simple way to create arbitrary
# iterator, utilizing object state (or not, if you are fan
# of functional), magic and nuclear waste--no kittens hurt.
pass # don't forget to add the next() method
def __iter__(self):
return self.create_iterator()
注:
I'll repeat again: iterator is not iterable. Iterator cannot be used as a "source" in for loop. What for loop primarily needs is __iter__() (that returns something with next()). Of course, for is not the only iteration loop, so above applies to some other constructs as well (while...). Iterator's next() can throw StopIteration to stop iteration. Does not have to, though, it can iterate forever or use other means. In the above "thought process", _i does not really exist. I've made up that name. There's a small change in Python 3.x: next() method (not the built-in) now must be called __next__(). Yes, it should have been like that all along. You can also think of it like this: iterable has the data, iterator pulls the next item
免责声明:我不是任何Python解释器的开发人员,所以我真的不知道解释器“在想什么”。上面的思考仅仅是我从其他解释、实验和一个Python新手的实际经验中对这个主题的理解。
以下是我在教授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
我不知道这是否对任何人都有帮助,但我总是喜欢在脑子里把概念形象化,以便更好地理解它们。所以,就像我有一个小儿子一样,我用砖块和白纸来想象迭代器/迭代器的概念。
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
>>>
不知道有没有帮助,但对我有帮助。如果有人能确认/纠正这个概念的可视化,我会很感激。这会帮助我了解更多。
下面是我的小抄:
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 = [1, 2]
iterator = iter(iterable)
print(iterator.__next__())
print(iterator.__next__())
so,
Iterable是一个可以循环的对象。例如,列表,字符串,元组等。 在iterable对象上使用iter函数将返回一个迭代器对象。 现在这个迭代器对象有一个名为__next__的方法(在Python 3中,或者在Python 2中只是next),通过它你可以访问iterable的每个元素。
所以, 以上代码的输出为:
1
2
推荐文章
- 操作系统。makdirs在我的路径上不理解“~”
- 如何在Django模板中获得我的网站的域名?
- 在django Forms中定义css类
- 如何在Python中scp ?
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码