English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Python 文件操作

Python 对象和类

Python 日期和时间

Python 高级知识

Python 参考手册

Iterateurs en Python

迭代器是可以迭代的对象。 在本教程中,您将学习迭代器的工作原理以及如何使用__iter__和__next__方法构建自己的迭代器。

Python中的迭代器是什么?

迭代器在Python中无处不在。它们在for循环,理解,生成器等中优雅地实现,但却隐藏在眼皮底下。

Python中的Iterator只是一个可以迭代的对象。一个将返回数据的对象,一次返回一个元素。

从技术上讲,Python 迭代器对象必须实现两个特殊方法,__iter__()和__next__()统称为迭代器协议.

如果我们可以从对象获得迭代器,则该对象称为迭代。Python中的大多数内置容器(例如:listtuplestring等)都是可迭代的。

iter()函数(也就是__iter__()方法)从它们返回一个迭代器。

通过Python中的迭代器进行迭代

我们使用该next()函数手动遍历迭代器的所有项目。 当我们到达末尾并且没有更多数据要返回时,它将引发StopIteration。 以下是一个示例。。

# 定义一个列表
my_list = [4, 7, 0, 3]
# 使用iter()获得迭代器
my_iter = iter(my_list)
## 使用iter()获得迭代器 
# Sortie 4
print(next(my_iter))
# Sortie 7
print(next(my_iter))
## next(obj)与obj .__ next __()相同
# Sortie 0
print(my_iter.__next__())
# Sortie 3
print(my_iter.__next__())
## Cela entraînera une erreur, il n'y a plus d'éléments
next(my_iter)

Une méthode plus élégante pour itérer automatiquement est d'utiliserBoucle forEn utilisant cette méthode, nous pouvons itérer sur n'importe quel objet qui peut retourner un itérateur, par exemple une liste, une chaîne, un fichier, etc.

>>> for element in my_list:
...    print(element)
...     
4
7
0
3

Comment fonctionne réellement la boucle for ?

Comme nous l'avons vu dans l'exemple précédent, la boucle for peut parcourir automatiquement une liste.

En réalité, la boucle for peut itérer n'importe quel objet itérable. Laissons-nous examiner de plus près comment la boucle for est réellement implémentée en Python.

for element in iterable:
    # Faites quelque chose de l'élément

c'est en fait implémenté comme.

# Créer un objet itérateur iterable
iter_obj = iter(iterable)
# Boucle infinie
while True:
    try:
        # Obtenir l'élément suivant
        element = next(iter_obj)
        # Faites quelque chose de l'élément
    except StopIteration:
        # Si StopIteration est levée, sort de la boucle
        break

Par conséquent, à l'intérieur, la boucle for crée un objet itérateur iter_obj en appelant iter() sur iterable.

Ironiquement, ce boucle for est en fait infinieBoucle while.

Dans la boucle, il appelle next() pour obtenir l'élément suivant et utilise cette valeur pour exécuter le corps de la boucle for. Une fois tous les éléments terminés, StopIteration est lancé, il est capturé à l'intérieur et la boucle se termine. Notez que toute autre exception passera.

Construire son propre itérateur en Python

Il est facile de construire un itérateur à partir de zéro en Python. Nous devons simplement implémenter ces méthodes __iter__() et __next__().

La méthode __iter__() retourne l'objet itérateur lui-même. Si nécessaire, vous pouvez effectuer certaines initialisations.

La méthode __next__() doit retourner l'élément suivant de la séquence. Lorsque nous atteignons la fin, ainsi que lors des appels suivants, elle doit lever StopIteration.

Ici, nous montrons un exemple qui nous fournira2puissance. L'exponentiel de puissance va de 0 à un nombre numérique défini par l'utilisateur.

class PowTwo:
    """Classe d'itérateur pour implémenter"
             "puissance de deux"
    def __init__(self, max = 0):
        self.max = max
    def __iter__(self):
        self.n = 0
        return self
    def __next__(self):
        if self.n <= self.max:
            result = 2 ** self.n
            self.n += 1
            return result
        else:
            raise StopIteration

Maintenant, nous pouvons créer un itérateur et itérer comme suit.

>>> a = PowTwo(4)
>>> i = iter(a)
>>> next(i)
1
>>> next(i)
2
>>> next(i)
4
>>> next(i)
8
>>> next(i)
16
>>> next(i)
Traceback (most recent call last):
...
StopIteration

Nous pouvons également utiliser une boucle for pour itérer sur une classe d'itérateur.

>>> for i in PowTwo(5):
...     print(i)
...     
1
2
4
8
16
32

Python infinite iterators

The items in an iterator object do not have to be exhausted. There may be infinite iterators (which will never end). When dealing with such iterators, we must be careful.

This is a simple example of demonstrating an infinite iterator.

Built-in functions The iter() function can be called with two parameters, where the first parameter must be a callable object (function), and the second parameter is the marker. The iterator calls this function until the returned value equals the marker value.

>>> int()
0
>>> inf = iter(int,1)
>>> next(inf)
0
>>> next(inf)
0

We can see that the int() function always returns 0. Therefore, it can be used as iter(int,1) Passing will return an iterator that calls int() until the returned value equals1. This will never happen, and we get an infinite iterator.

We can also build our own infinite iterators. Theoretically, the following iterator will return all odd numbers.

class InfIter:
    """The infinite iterator returns all
                 Odd numbers """
    def __iter__(self):
        self.num = 1
        return self
    def __next__(self):
        num = self.num
        self.num += 2
        return num

Run as follows.

>>> a = iter(InfIter())
>>> next(a)
1
>>> next(a)
3
>>> next(a)
5
>>> next(a)
7

...

Be careful to include a termination condition when iterating over these types of infinite iterators.

The advantage of using iterators is that they save resources. As shown above, we can get all odd numbers without having to store the entire number system in memory. In theory, we can include an infinite number of items in a finite amount of memory.

Iterators also make our code look cool.

There is an easy way to create iterators in Python. For more information, please visit:Python generator yield.