-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgroupby_example.py
48 lines (34 loc) · 1.05 KB
/
groupby_example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from itertools import groupby, tee
alunos = [
{'nome': 'Luiz', 'nota': 'A'},
{'nome': 'Letícia', 'nota': 'B'},
{'nome': 'Fabrício', 'nota': 'A'},
{'nome': 'Rosemary', 'nota': 'C'},
{'nome': 'Joana', 'nota': 'D'},
{'nome': 'João', 'nota': 'A'},
{'nome': 'Eduardo', 'nota': 'B'},
{'nome': 'André', 'nota': 'C'},
{'nome': 'Anderson', 'nota': 'B'},
]
def ordena(item):
return item['nota']
alunos.sort(key=ordena)
alunos_agrupados = groupby(alunos, ordena)
'''
# Sem tee (com list)
for agrupamento, valores_agrupados in alunos_agrupados:
valores = list(valores_agrupados)
print(f'Agrupamento: {agrupamento}')
for aluno in valores:
print(f'\t{aluno}')
quantidade = len(valores)
print(f'\t{quantidade} alunos tiraram nota {agrupamento}')
'''
# Com tee
for agrupamento, valores_agrupados in alunos_agrupados:
v1, v2 = tee(valores_agrupados)
print(f'Agrupamento: {agrupamento}')
for aluno in v1:
print(f'\t{aluno}')
quantidade = len(list(v2))
print(f'\t{quantidade} alunos tiraram nota {agrupamento}')