Created
March 27, 2021 18:56
-
-
Save luizomf/2db5239b87b1030f50ad27c9f7be118d to your computer and use it in GitHub Desktop.
Groupby example in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fala professor,
A diferença desse código foi apenas que o ordena foi definido como função, certo?