205 lines
4.7 KiB
Markdown
205 lines
4.7 KiB
Markdown
# itertools
|
|
|
|
El módulo itertools es un conjunto de herramientas para manejar iteradores.
|
|
Los iteradores son un tipo de dato que usar para iterar, ejm. en un loop for.
|
|
|
|
Un iterator es un objeto sobre el cual se puede iterar, es decir, se pueden
|
|
recorrer todos sus valores.
|
|
|
|
Un iterador es un objeto que contiene un número contable de valores.
|
|
|
|
En python un iterador es un obj. que implementa el protocolo iterator, que
|
|
consiste en los métodos **`__iter__()`** y **`__next__()`**.
|
|
|
|
Listas, tuplas, diccionarios y sets, son objetos iterables. De los cuales se
|
|
puede obtener un iterador, metodo iter()
|
|
|
|
Algunas herramientas de los iteradores son:
|
|
- [product](https://gitea.kickto.net/devfzn/Apuntes_Python/src/branch/master/02_conceptos/07_itertools#product)
|
|
- [permutations](https://gitea.kickto.net/devfzn/Apuntes_Python/src/branch/master/02_conceptos/07_itertools#permutations)
|
|
- [combinations, combinations_with_replacement](https://gitea.kickto.net/devfzn/Apuntes_Python/src/branch/master/02_conceptos/07_itertools#combinations)
|
|
- [accumulate (multiplicación, max)](https://gitea.kickto.net/devfzn/Apuntes_Python/src/branch/master/02_conceptos/07_itertools#accumulate)
|
|
- [groupby](https://gitea.kickto.net/devfzn/Apuntes_Python/src/branch/master/02_conceptos/07_itertools#groupby)
|
|
- [infinite iterators (count, cycle, repeat)](https://gitea.kickto.net/devfzn/Apuntes_Python/src/branch/master/02_conceptos/07_itertools#infinite-iterators)
|
|
|
|
|
|
### product
|
|
|
|
```python
|
|
from itertools import product
|
|
|
|
a = [1, 2]
|
|
b = [3, 4]
|
|
prod = product(a, b) # <itertools.product object at ...>
|
|
list(prod)
|
|
# [(1, 3), (1, 4),
|
|
# (2, 3), (2, 4)]
|
|
|
|
a = [1, 2]
|
|
b = [3]
|
|
prod = product(a, b, repeat=2) # <itertools.product object at ...>
|
|
list(prod)
|
|
# [(1, 3, 1, 3), (1, 3, 2, 3),
|
|
# (2, 3, 1, 3), (2, 3, 2, 3)]
|
|
```
|
|
----
|
|
|
|
### permutations
|
|
|
|
Todos los posibles ordenes de una entrada
|
|
|
|
```python
|
|
from itertools import permutations
|
|
|
|
a = [1,2,3]
|
|
perm = permutations(a)
|
|
list(perm)
|
|
# [(1, 2, 3), (1, 3, 2),
|
|
# (2, 1, 3), (2, 3, 1),
|
|
# (3, 1, 2), (3, 2, 1)]
|
|
|
|
# especificar largo de permutaciones
|
|
perm = permutations(a, 2)
|
|
list(perm)
|
|
# [(1, 2), (1, 3),
|
|
# (2, 1), (2, 3),
|
|
# (3, 1), (3, 2)]
|
|
```
|
|
----
|
|
|
|
### combinations
|
|
|
|
Realiza todas las posibles combinaciones, según largo
|
|
pasado como 2do argumento (no repite elementos).
|
|
|
|
```python
|
|
from itertools import (combinations,
|
|
combinations_with_replacement,
|
|
accumulate)
|
|
|
|
a = [1,2,3,4]
|
|
comb = combinations(a, 2)
|
|
list(comb)
|
|
# [(1, 2), (1, 3),
|
|
# (1, 4), (2, 3),
|
|
# (2, 4), (3, 4)]
|
|
```
|
|
|
|
### combinations_with_replacement
|
|
|
|
Igual que el anterior pero repite elementos
|
|
|
|
```python
|
|
comb_wr = combinations_with_replacement(a, 2)
|
|
list(comb_wr)
|
|
# [(1, 1), (1, 2), (1, 3), (1, 4), (2, 2),
|
|
# (2, 3), (2, 4), (3, 3), (3, 4), (4, 4)]
|
|
```
|
|
|
|
### accumulate
|
|
|
|
Acumula(suma o concatena) elemementos (del mismo tipo).
|
|
|
|
```python
|
|
accum = accumulate(a)
|
|
list(accum) # [1,3,6,10]
|
|
|
|
b = ['a', 'b', 'cedario']
|
|
accum2 = accumulate(b)
|
|
list(accum2) # ['a', 'ab', 'abcedario']
|
|
|
|
# accumulate, multiplicación
|
|
import operator
|
|
accum_mult = accumulate(a, func=operator.mul)
|
|
list(accum_mult) # [1, 2, 6, 24]
|
|
|
|
# accumulate, max
|
|
c = [1, 2, 5, 3, 4]
|
|
accm_max = accumulate(c, func=max)
|
|
list(accm_max) # [1, 2, 5, 5, 5]
|
|
```
|
|
----
|
|
|
|
### groupby
|
|
|
|
Crea un iterador que retorna keys y groups de un elemento iterable
|
|
```python
|
|
from itertools import groupby
|
|
|
|
#def menor_q_3(x):
|
|
# return x < 3
|
|
# reemplazado por funcion lambda
|
|
|
|
a = [1, 2, 3, 4]
|
|
group_obj = groupby(a, key=lambda x: x<3)
|
|
for key, value in group_obj:
|
|
print(key, list(value))
|
|
# True [1, 2]
|
|
# False [3, 4]
|
|
|
|
personas = [{'nombre': 'Zerafio', 'edad': 26},
|
|
{'nombre': 'Raber', 'edad': 26},
|
|
{'nombre': 'Estor', 'edad': 58},
|
|
{'nombre': 'Gunter', 'edad': 26}]
|
|
|
|
group_obj = groupby(personas, key=lambda x: x['edad'])
|
|
for key, value in group_obj:
|
|
print(key, list(value))
|
|
# agrupa solo si los elementos son consecutivos?
|
|
# 26 [{'nombre': 'Zerafio', 'edad': 26}, {'nombre': 'Raber', 'edad': 26}]
|
|
# 58 [{'nombre': 'Estor', 'edad': 58}]
|
|
# 26 [{'nombre': 'Gunter', 'edad': 26}]
|
|
```
|
|
----
|
|
|
|
### infite iterators
|
|
#### count
|
|
Itera infinitamente desde un numero
|
|
```python
|
|
from itertools import count
|
|
|
|
for i in count(10):
|
|
print(i)
|
|
if i == 15:
|
|
break
|
|
# 10
|
|
# 11
|
|
# 12
|
|
# 13
|
|
# 14
|
|
# 15
|
|
```
|
|
|
|
#### cycle
|
|
Itera infinitamente un iterable
|
|
```python
|
|
from itertools import cycle
|
|
a = [1, 2, 3]
|
|
cont = 0
|
|
for i in cycle(a):
|
|
print(i)
|
|
cont += 1
|
|
if cont > 8:
|
|
break
|
|
# 1
|
|
# 2
|
|
# 3
|
|
# 1
|
|
# 2
|
|
# 3
|
|
```
|
|
|
|
#### repeat
|
|
Repite el argumento pasado infinitamente,
|
|
o hasta el valor pasado como segundo argumento
|
|
```python
|
|
from itertools import repeat
|
|
|
|
for i in repeat(1, 4):
|
|
print(i)
|
|
# 1
|
|
# 1
|
|
# 1
|
|
# 1
|
|
```
|