究竟什么是迭代器、可迭代和迭代?
问题描述
Python中iterable"、iterator"、iteration"最基本的定义是什么?
What is the most basic definition of "iterable", "iterator" and "iteration" in Python?
我已经阅读了多个定义,但我无法确定确切的含义,因为它仍然无法理解.
I have read multiple definitions but I am unable to identify the exact meaning as it still won't sink in.
有人可以帮我用外行术语来解释这 3 个定义吗?
Can someone please help me with the 3 definitions in layman terms?
解决方案
迭代是一个总称,一个接一个地取某事物的每一项.每当您使用循环(显式或隐式)遍历一组项目时,这就是迭代.
Iteration is a general term for taking each item of something, one after another. Any time you use a loop, explicit or implicit, to go over a group of items, that is iteration.
在 Python 中,iterable 和 iterator 有特定的含义.
In Python, iterable and iterator have specific meanings.
iterable 是具有 __iter__
方法的对象,该方法返回 iterator,或定义 __getitem__
可以采用从零开始的顺序索引的方法(并在索引不再有效时引发 IndexError
).所以 iterable 是一个可以从中获取 iterator 的对象.
An iterable is an object that has an __iter__
method which returns an iterator, or which defines a __getitem__
method that can take sequential indexes starting from zero (and raises an IndexError
when the indexes are no longer valid). So an iterable is an object that you can get an iterator from.
iterator 是具有 next
(Python 2) 或 __next__
(Python 3) 方法的对象.
An iterator is an object with a next
(Python 2) or __next__
(Python 3) method.
每当你在 Python 中使用 for
循环、map
或列表推导等时,都会自动调用 next
方法从iterator中获取每一项,从而经历iteration的过程.
Whenever you use a for
loop, or map
, or a list comprehension, etc. in Python, the next
method is called automatically to get each item from the iterator, thus going through the process of iteration.
本教程的迭代器部分和标准类型页面的迭代器类型部分.了解基础知识后,请尝试函数式编程 HOWTO 的迭代器部分.
A good place to start learning would be the iterators section of the tutorial and the iterator types section of the standard types page. After you understand the basics, try the iterators section of the Functional Programming HOWTO.
相关文章