迭代器、迭代器和迭代到底是什么?

迭代器、迭代器和迭代到底是什么?

Python中“迭代”、“迭代器”和“迭代”的最基本定义是什么?

我已经阅读了多个定义,但我无法确定确切的含义,因为它仍然不会沉入其中。

有谁能帮我解决这三个外行术语的定义吗?


MYYA
浏览 2150回答 4
4回答

慕哥9229398

迭代法是一个笼统的术语,用来指一个接一个地拿走一件的每一件东西。每当您使用一个循环(显式或隐式)遍历一组项时,即迭代。在Python里,可迭代和迭代器有特定的含义。阿可迭代是具有__iter__方法返回迭代器,或者定义__getitem__方法,该方法可以从零开始接受顺序索引(并引发IndexError当索引不再有效时)。所以可迭代是一个可以获得迭代器从…。阿迭代器是具有next(Python 2)或__next__(Python 3)方法。无论何时使用for循环,或map,或列表理解等。在Python中,next方法自动调用,以从迭代器,从而经历了…的过程。迭代法.一个开始学习的好地方是本教程的迭代器部分而标准类型页的迭代器类型部分..在您了解了基本知识之后,尝试函数编程方法的迭代器部分.

手掌心

下面是我在教学Python课程时使用的解释:ITERABLE是:任何可以循环的东西(例如,您可以在字符串或文件上循环)或可以出现在for-循环右侧的任何内容:for x in iterable: ...或任何你可以调用的东西iter()它将返回一个ITERATOR:iter(obj)或定义__iter__返回一个新的ITERATOR,或者它可能有一个__getitem__方法,适用于索引查找。ITERATOR是一个对象:如果状态记得它在迭代过程中所处的位置,带着__next__方法:返回迭代中的下一个值。将状态更新为指向下一个值。发出信号时,它是通过提高StopIteration这是可自我迭代的(意思是它有一个__iter__方法返回self).注:这个__next__方法在Python 3中是拼写的。next在Python 2中,以及内建函数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 completeTraceback (most recent call last):...                    StopIteration>>> iter(t) is t   # the iterator is self-iterable

达令说

迭代是具有__iter__()方法。它可能会重复多次,例如list()S和tuple()S.迭代器是迭代的对象。由__iter__()方法,则通过自己的方法返回自身。__iter__()方法,并具有next()方法(__next__()(见3.x)。迭代是调用以下内容的过程next()RESP.__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 b21>>> next(b1)3>>> next(b1)Traceback (most recent call last):&nbsp; File "<stdin>", line 1, in <module>StopIteration>>> b1 = iter(a) # new one, start over>>> next(b1)1
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python