English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Los iteradores son objetos que son iterables. En este tutorial, aprenderás cómo funciona un iterador y cómo construir tu propio iterador utilizando los métodos __iter__ y __next__.
Los iteradores en Python están en todas partes. Se implementan elegantemente en bucles for, comprehensions, generadores, etc., pero se esconden a simple vista.
Un Iterator en Python es solo algo que es iterableobjeto。Un objeto que devuelve datos, uno a la vez.
Técnicamente, Python objeto iteradorSe deben implementar dos métodos especiales, __iter__() y __next__(), que se denominanprotocolo de iterador.
Si podemos obtener un iterador de un objeto, ese objeto se llamaiterableiterar. La mayoría de los contenedores integrados en Python (por ejemplo:lista,tupla,cadenaetc.) son iterables.
La función iter() (también conocida como el método __iter__() ) devuelve un iterador.
Usamos la función next() para recorrer manualmente todos los elementos del iterador. Cuando llegamos al final y no hay más datos que devolver, lanzará StopIteration. Aquí hay un ejemplo...
# Definir una lista my_list = [4, 7, 0, 3] # Obtener un iterador con iter() my_iter = iter(my_list) ## Obtener un iterador con iter() #Salida 4 print(next(my_iter)) #Salida 7 print(next(my_iter)) ## next(obj)es equivalente a obj .__ next __() #Salida 0 print(my_iter.__next__()) #Salida 3 print(my_iter.__next__()) ## Esto causará un error, no quedan más elementos next(my_iter)
Una manera más elegante de iterar automáticamente es usarbucle forCon este método, podemos iterar cualquier objeto que pueda devolver un iterador, como listas, cadenas, archivos, etc.
>>> for element in my_list: ... print(element) ... 4 7 0 3
Como vimos en el ejemplo anterior, el bucle for puede recorrer automáticamente una lista.
En realidad, el bucle for puede iterar cualquier objeto iterable. Vamos a ver con detalle cómo se realiza el bucle for en Python.
for elemento en iterable: # Hacer algo con el elemento
es realmente implementado como.
# Crear un objeto de iterador iterable iter_obj = iter(iterable) # Bucle infinito while True: try: # Obtener el siguiente elemento elemento = next(iter_obj) # Hacer algo con el elemento except StopIteration: # Si se lanza StopIteration, saldrá del bucle romper
Por lo tanto, internamente, el bucle for crea un objeto de iterador iter_obj llamando a iter() en el iterable.
Irónicamente, este bucle for es realmente infinitoBucle while.
Dentro del bucle, llama a next() para obtener el siguiente elemento y usar ese valor para ejecutar el cuerpo del bucle for. Cuando se hayan utilizado todos los elementos, se lanza StopIteration, que se captura internamente y el bucle termina. Nota, cualquier otro tipo de excepción pasará.
Es fácil construir un iterador desde cero en Python. Solo necesitamos implementar estos métodos __iter__() y __next__().
El método __iter__() devuelve el objeto de iterador en sí. Puede realizar alguna inicialización si es necesario.
El método __next__() debe devolver el siguiente elemento de la secuencia. Debe lanzar StopIteration cuando se alcance el final y en las llamadas posteriores.
Aquí, mostramos un ejemplo que nos proporcionará2la potencia. La potencia de exponente va de 0 al número configurado por el usuario.
class PowTwo: """Implementar la clase de iterador" "potencia de dos" 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 devolver result else: levantar StopIteration
Ahora, podemos crear un iterador y realizar la iteración de la siguiente manera.
>>> a = PowTwo(4) >>> i = iter(a) >>> next(i) 1 >>> next(i) 2 >>> next(i) 4 >>> next(i) 8 >>> next(i) 16 >>> next(i) Traceback (más reciente llamada última): ... StopIteration
Podemos usar un bucle for para iterar sobre la clase de iterador.
>>> for i en PowTwo(5) ... imprimir(i) ... 1 2 4 8 16 32
The items in an iterator object do not have to be exhausted. There may be infinite iterators (that 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.