Funciones comunes en Python.
zip()
a = ("John", "Charles", "Mike")
b = ("Jenny", "Christy", "Monica")
x = zip(a, b)
# use the tuple() function to display a readable version of the result:
print(tuple(x))
# SALIDA
# (('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica'))
pairwise()
from itertools import pairwise # Python 3.10
cadena = 'ABCDEFG' # Iterable
# pairwise('ABCDEFG') --> AB BC CD DE EF FG
for primero, segundo in pairwise(cadena):
print(f'{primero}{segundo} ', end='')
print()
# SALIDA: AB BC CD DE EF FG
cycle()
from itertools import cycle
cadena = 'ABCD' # Iterable
# cycle('ABCD') --> A B C D A B C D A B C D ...
iterador = cycle(cadena)
for _ in range(1, 5):
elemento = next(iterador)
print(elemento) # Elemento 4: D
map()
from itertools import repeat # Crea un iterable con el valor que se le pase
def myfunc(a):
return len(a)
x = map(myfunc, ('apple', 'banana', 'cherry'))
print(x) # <map object at 0x056D44F0>
#convert the map into a list, for readability:
print(list(x)) # SALIDA: [5, 6, 6]
print(list(map(pow, range(10), repeat(2)))) # pow() necesita 2 argumentos. n^2
# SALIDA: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]