Itertools de Python

Itertool de Python es un módulo que proporciona varias funciones que funcionan en iteradores para producir iteradores complejos. Este módulo funciona como una herramienta rápida y eficiente en memoria que se usa solo o en combinación para formar álgebra iteradora
Por ejemplo, supongamos que hay dos listas y desea multiplicar sus elementos. Puede haber varias formas de lograr esto. Uno puede estar utilizando el enfoque ingenuo, es decir, iterando a través de los elementos de la lista simultáneamente y multiplicándolos. Y otro enfoque puede ser usar la función de mapa, es decir, pasar el operador mul como primer parámetro a la función de mapa y Listas como el segundo y tercer parámetro de esta función. Veamos el tiempo que toma cada enfoque. 

Python3

# Python program to demonstrate
# iterator module
 
 
import operator
import time
 
# Defining lists
L1 = [1, 2, 3]
L2 = [2, 3, 4]
 
# Starting time before map
# function
t1 = time.time()
 
# Calculating result
a, b, c = map(operator.mul, L1, L2)
 
# Ending time after map
# function
t2 = time.time()
 
# Time taken by map function
print("Result:", a, b, c)
print("Time taken by map function: %.6f" %(t2 - t1))
 
# Starting time before naive
# method
t1 = time.time()
 
# Calculating result using for loop
print("Result:", end = " ")
for i in range(3):
    print(L1[i] * L2[i], end = " ")
     
# Ending time after naive
# method
t2 = time.time()
print("\nTime taken by for loop: %.6f" %(t2 - t1))

Producción:

Result: 2 6 12
Time taken by map function: 0.000005
Result: 2 6 12 
Time taken by for loop: 0.000014

En el ejemplo anterior, se puede ver que el tiempo que tarda la función map es aproximadamente la mitad del tiempo que tarda el bucle for. Esto demuestra que las itertools son herramientas rápidas y eficientes en memoria.

Los diferentes tipos de iteradores proporcionados por este módulo son: 

iteradores infinitos

El iterador en Python es cualquier tipo de Python que se puede usar con un ‘for in loop’. Las listas, tuplas, diccionarios y conjuntos de Python son ejemplos de iteradores incorporados. Pero no es necesario que un objeto iterador tenga que agotar, a veces puede ser infinito. Estos tipos de iteradores se conocen como iteradores infinitos .

Python proporciona tres tipos de iteradores infinitos: 

  • count (inicio, paso): este iterador comienza a imprimir desde el número de «inicio» e imprime infinitamente . Si se mencionan pasos, los números se omiten; de lo contrario, el paso es 1 de forma predeterminada. Vea el siguiente ejemplo para su uso con for in loop.
    Ejemplo:

Python3

# Python program to demonstrate
# infinite iterators
   
import itertools
   
# for in loop
for i in itertools.count(5, 5):
    if i == 35:
        break
    else:
        print(i, end =" ")

Producción:

5 10 15 20 25 30
  • ciclo (iterable): este iterador imprime todos los valores en orden desde el contenedor pasado. Reinicia la impresión desde el principio nuevamente cuando todos los elementos se imprimen de manera cíclica .
    Ejemplo 1:

Python3

# Python program to demonstrate
# infinite iterators
   
import itertools
   
count = 0
   
# for in loop
for i in itertools.cycle('AB'):
    if count > 7:
        break
    else:
        print(i, end = " ")
        count += 1

Producción:

A B A B A B A B 

Ejemplo 2: Uso de la siguiente función.

Python3

# Python program to demonstrate
# infinite iterators
   
import itertools
   
l = ['Geeks', 'for', 'Geeks']
   
# defining iterator
iterators = itertools.cycle(l)
   
# for in loop
for i in range(6):
       
    # Using next function
    print(next(iterators), end = " ")

Iteradores combinatorios 
Salida:

Geeks for Geeks Geeks for Geeks 
  • repeat(val, num): este iterador imprime repetidamente el valor pasado un número infinito de veces. Si se menciona la palabra clave opcional num, se imprime repetidamente num número de veces.
    Ejemplo:

Python3

# Python code to demonstrate the working of  
# repeat() 
     
# importing "itertools" for iterator operations 
import itertools 
     
# using repeat() to repeatedly print number 
print ("Printing the numbers repeatedly : ") 
print (list(itertools.repeat(25, 4)))

Producción:

Printing the numbers repeatedly : 
[25, 25, 25, 25]

iteradores combinatorios

Los generadores recursivos que se utilizan para simplificar construcciones combinatorias como permutaciones, combinaciones y productos cartesianos se denominan iteradores combinatorios.
En Python hay 4 iteradores combinatorios: 

  • Producto(): esta herramienta calcula el producto cartesiano de iterables de entrada. Para calcular el producto de un iterable consigo mismo, usamos el argumento de palabra clave de repetición opcional para especificar el número de repeticiones. La salida de esta función son tuplas ordenadas.
    Ejemplo:

Python3

# import the product function from itertools module
from itertools import product
   
print("The cartesian product using repeat:")
print(list(product([1, 2], repeat = 2)))
print()
   
print("The cartesian product of the containers:")
print(list(product(['geeks', 'for', 'geeks'], '2')))
print()
   
print("The cartesian product of the containers:")
print(list(product('AB', [3, 4])))

Producción:

The cartesian product using repeat:
[(1, 1), (1, 2), (2, 1), (2, 2)]

The cartesian product of the containers:
[('geeks', '2'), ('for', '2'), ('geeks', '2')]

The cartesian product of the containers:
[('A', 3), ('A', 4), ('B', 3), ('B', 4)]
  • Permutaciones(): Permutaciones(), como el nombre habla por sí mismo, se usa para generar todas las permutaciones posibles de un iterable . Todos los elementos se tratan como únicos en función de su posición y no de sus valores. Esta función toma un iterable y group_size, si el valor de group_size no se especifica o es igual a Ninguno, entonces el valor de group_size se convierte en la longitud del iterable.
    Ejemplo:

Python3

# import the product function from itertools module
from itertools import permutations
   
print ("All the permutations of the given list is:") 
print (list(permutations([1, 'geeks'], 2)))
print()
 
print ("All the permutations of the given string is:") 
print (list(permutations('AB')))
print()
   
print ("All the permutations of the given container is:") 
print(list(permutations(range(3), 2)))

Producción:

All the permutations of the given list is:
[(1, 'geeks'), ('geeks', 1)]

All the permutations of the given string is:
[('A', 'B'), ('B', 'A')]

All the permutations of the given container is:
[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
  • Combinaciones(): este iterador imprime todas las combinaciones posibles (sin reemplazo) del contenedor pasado en argumentos en el tamaño de grupo especificado en orden ordenado.
    Ejemplo:

Python3

# import combinations from itertools module
   
from itertools import combinations
   
print ("All the combination of list in sorted order(without replacement) is:") 
print(list(combinations(['A', 2], 2)))
print()
   
print ("All the combination of string in sorted order(without replacement) is:")
print(list(combinations('AB', 2)))
print()
   
print ("All the combination of list in sorted order(without replacement) is:")
print(list(combinations(range(2), 1)))

Producción:

All the combination of list in sorted order(without replacement) is:
[('A', 2)]

All the combination of string in sorted order(without replacement) is:
[('A', 'B')]

All the combination of list in sorted order(without replacement) is:
[(0, ), (1, )]
  • Combinations_with_replacement(): Esta función devuelve una subsecuencia de longitud n de los elementos del iterable donde n es el argumento que toma la función para determinar la longitud de las subsecuencias generadas por la función. Los elementos individuales pueden repetirse en la función combinaciones_con_reemplazo.
    Ejemplo:

Python3

# import combinations from itertools module
   
from itertools import combinations_with_replacement
   
print ("All the combination of string in sorted order(with replacement) is:")
print(list(combinations_with_replacement("AB", 2)))
print()
   
print ("All the combination of list in sorted order(with replacement) is:")
print(list(combinations_with_replacement([1, 2], 2)))
print()
   
print ("All the combination of container in sorted order(with replacement) is:")
print(list(combinations_with_replacement(range(2), 1)))

Producción:

All the combination of string in sorted order(with replacement) is:
[('A', 'A'), ('A', 'B'), ('B', 'B')]

All the combination of list in sorted order(with replacement) is:
[(1, 1), (1, 2), (2, 2)]

All the combination of container in sorted order(with replacement) is:
[(0, ), (1, )]

Iteradores de terminación

Los iteradores de terminación se utilizan para trabajar en las secuencias de entrada cortas y producir la salida en función de la funcionalidad del método utilizado.

Los diferentes tipos de iteradores de terminación son: 

  • acumular (iter, func): este iterador toma dos argumentos, el objetivo iterable y la función que se seguiría en cada iteración del valor en el objetivo. Si no se pasa ninguna función, la adición se realiza de forma predeterminada. Si el iterable de entrada está vacío, el iterable de salida también estará vacío.
    Ejemplo:

Python3

# Python code to demonstrate the working of 
# accumulate()
 
 
import itertools
import operator
 
# initializing list 1
li1 = [1, 4, 5, 7]
   
# using accumulate()
# prints the successive summation of elements
print ("The sum after each iteration is : ", end ="")
print (list(itertools.accumulate(li1)))
   
# using accumulate()
# prints the successive multiplication of elements
print ("The product after each iteration is : ", end ="")
print (list(itertools.accumulate(li1, operator.mul)))
   
# using accumulate()
# prints the successive summation of elements
print ("The sum after each iteration is : ", end ="")
print (list(itertools.accumulate(li1)))
   
# using accumulate()
# prints the successive multiplication of elements
print ("The product after each iteration is : ", end ="")
print (list(itertools.accumulate(li1, operator.mul)))

Producción:

The sum after each iteration is : [1, 5, 10, 17]
The product after each iteration is : [1, 4, 20, 140]
The sum after each iteration is : [1, 5, 10, 17]
The product after each iteration is : [1, 4, 20, 140]
  • chain(iter1, iter2..): Esta función se utiliza para imprimir todos los valores en objetivos iterables uno tras otro mencionados en sus argumentos.
    Ejemplo:

Python3

# Python code to demonstrate the working of 
# and chain()
   
 
import itertools
 
# initializing list 1
li1 = [1, 4, 5, 7]
   
# initializing list 2
li2 = [1, 6, 5, 9]
   
# initializing list 3
li3 = [8, 10, 5, 4]
 
# using chain() to print all elements of lists
print ("All values in mentioned chain are : ", end ="")
print (list(itertools.chain(li1, li2, li3)))

Producción:

All values in mentioned chain are : [1, 4, 5, 7, 1, 6, 5, 9, 8, 10, 5, 4]
  • chain.from_iterable(): Esta función se implementa de manera similar a una string() pero el argumento aquí es una lista de listas o cualquier otro contenedor iterable.
    Ejemplo:

Python3

# Python code to demonstrate the working of 
# chain.from_iterable()
 
 
import itertools
 
 
# initializing list 1
li1 = [1, 4, 5, 7]
   
# initializing list 2
li2 = [1, 6, 5, 9]
   
# initializing list 3
li3 = [8, 10, 5, 4]
   
# initializing list of list
li4 = [li1, li2, li3]
 
# using chain.from_iterable() to print all elements of lists
print ("All values in mentioned chain are : ", end ="")
print (list(itertools.chain.from_iterable(li4)))

Producción:

All values in mentioned chain are : [1, 4, 5, 7, 1, 6, 5, 9, 8, 10, 5, 4]
  • compress(iter, selector): este iterador selecciona de forma selectiva los valores para imprimir del contenedor pasado de acuerdo con el valor de la lista booleana pasado como otros argumentos. Los argumentos correspondientes a boolean true se imprimen; de lo contrario, se omiten todos.
    Ejemplo:

Python3

# Python code to demonstrate the working of 
# and compress()
 
 
import itertools
 
 
# using compress() selectively print data values
print ("The compressed values in string are : ", end ="")
print (list(itertools.compress('GEEKSFORGEEKS', [1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0])))

Producción:

The compressed values in string are : ['G', 'F', 'G']
  • dropwhile(func, seq): este iterador comienza a imprimir los caracteres solo después de que func. en el argumento devuelve falso por primera vez.
    Ejemplo:

Python3

# Python code to demonstrate the working of 
# dropwhile()
 
 
import itertools
 
 
# initializing list 
li = [2, 4, 5, 7, 8]
   
# using dropwhile() to start displaying after condition is false
print ("The values after condition returns false : ", end ="")
print (list(itertools.dropwhile(lambda x : x % 2 == 0, li)))

Producción:

The values after condition returns false : [5, 7, 8]
  • filterfalse(func, seq): como sugiere el nombre, este iterador imprime solo valores que devuelven falso para la función pasada.
    Ejemplo:

Python3

# Python code to demonstrate the working of 
# filterfalse()
   
 
import itertools
   
# initializing list 
li = [2, 4, 5, 7, 8]
 
# using filterfalse() to print false values
print ("The values that return false to function are : ", end ="")
print (list(itertools.filterfalse(lambda x : x % 2 == 0, li)))

Producción:

The values that return false to function are : [5, 7]
  • islice(iterable, start, stop, step): Este iterador imprime selectivamente los valores mencionados en su contenedor iterable pasado como argumento. Este iterador toma 4 argumentos, contenedor iterable, posición inicial, posición final y paso.
    Ejemplo:

Python3

# Python code to demonstrate the working of 
# islice()
   
  
import itertools
   
# initializing list 
li = [2, 4, 5, 7, 8, 10, 20]
     
# using islice() to slice the list acc. to need
# starts printing from 2nd index till 6th skipping 2
print ("The sliced list values are : ", end ="")
print (list(itertools.islice(li, 1, 6, 2)))

Producción:

The sliced list values are : [4, 7, 10]
  • starmap(func., lista de tuplas): Este iterador toma una función y una lista de tuplas como argumento y devuelve el valor de acuerdo con la función de cada tupla de la lista.
    Ejemplo:

Python3

# Python code to demonstrate the working of 
# starmap()
   
 
import itertools
   
   
# initializing tuple list
li = [ (1, 10, 5), (8, 4, 1), (5, 4, 9), (11, 10, 1) ]
   
# using starmap() for selection value acc. to function
# selects min of all tuple values
print ("The values acc. to function are : ", end ="")
print (list(itertools.starmap(min, li)))

Producción:

The values acc. to function are : [1, 1, 4, 1]
  • takewhile(func, iterable): este iterador es lo opuesto a dropwhile(), imprime los valores hasta que la función devuelve falso por primera vez.
    Ejemplo:

Python3

# Python code to demonstrate the working of 
# takewhile()
   
 
import itertools
   
# initializing list 
li = [2, 4, 6, 7, 8, 10, 20]
   
# using takewhile() to print values till condition is false.
print ("The list values till 1st false value are : ", end ="")
print (list(itertools.takewhile(lambda x : x % 2 == 0, li )))

Producción:

The list values till 1st false value are : [2, 4, 6]
  • tee (iterador, cuenta): este iterador divide el contenedor en varios iteradores mencionados en el argumento.
    Ejemplo:

Python3

# Python code to demonstrate the working of 
# tee()
   
 
import itertools
   
# initializing list 
li = [2, 4, 6, 7, 8, 10, 20]
   
# storing list in iterator
iti = iter(li) 
   
# using tee() to make a list of iterators
# makes list of 3 iterators having same values.
it = itertools.tee(iti, 3)
   
# printing the values of iterators
print ("The iterators are : ")
for i in range (0, 3):
    print (list(it[i]))

Producción:

The iterators are : 
[2, 4, 6, 7, 8, 10, 20]
[2, 4, 6, 7, 8, 10, 20]
[2, 4, 6, 7, 8, 10, 20]
  • zip_longest(iterable1, iterable2, fillval): este iterador imprime los valores de iterables alternativamente en secuencia. Si uno de los iterables se imprime por completo, los valores restantes se completan con los valores asignados a fillvalue.
    Ejemplo:

Python3

# Python code to demonstrate the working of 
# zip_longest()
   
 
import itertools
   
# using zip_longest() to combine two iterables.
print ("The combined values of iterables is  : ")
print (*(itertools.zip_longest('GesoGes', 'ekfrek', fillvalue ='_' )))

Producción:

The combined values of iterables is  : 
('G', 'e') ('e', 'k') ('s', 'f') ('o', 'r') ('G', 'e') ('e', 'k') ('s', '_')

Publicación traducida automáticamente

Artículo escrito por nikhilaggarwal3 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *