問題描述
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.
這篇關于究竟什么是迭代器、可迭代和迭代?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!