迭代器、可迭代和迭代究竟是什么? [英] What exactly are iterator, iterable, and iteration?

查看:41
本文介绍了迭代器、可迭代和迭代究竟是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 中,iterableiterator 具有特定的含义.

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.

迭代器 是具有 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 方法从迭代器中获取每一项,从而经历迭代的过程.

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.

这篇关于迭代器、可迭代和迭代究竟是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆