究竟什么是迭代器、可迭代和迭代?

What exactly are iterator, iterable, and iteration?(究竟什么是迭代器、可迭代和迭代?)
本文介绍了究竟什么是迭代器、可迭代和迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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.

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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

python: iterating through a dictionary with list values(python:遍历具有列表值的字典)
What is the difference between chain and chain.from_iterable in itertools?(itertools中chain和chain.from_iterable有什么区别?)
python JSON only get keys in first level(python JSON只获取第一级的键)
Iterate over n successive elements of list (with overlapping)(迭代列表的 n 个连续元素(重叠))
Loop problem while iterating through a list and removing recurring elements(遍历列表并删除重复元素时出现循环问题)
Elegant way to skip elements in an iterable(跳过可迭代元素的优雅方式)