villares / material-aulas

Material para ensino introdutório de programação com Python em um contexto visual
https://abav.lugaralgum.com/material-aulas/
97 stars 70 forks source link

explicar `collections.Counter` talvez na página sobre dicionários? #132

Closed villares closed 5 months ago

villares commented 1 year ago

https://docs.python.org/3/library/collections.html#collections.Counter


with open('atividades.txt', 'r') as arquivo:
    atividades = arquivo.readlines()

novas_atividades = []
for atividade in atividades:
    a = atividade.strip()
    if a != '':
        novas_atividades.append(a)

from collections import Counter

contador = Counter(novas_atividades)

# print(contador)  # todo o dicionario contador
# print(contador.get('atividadeX'))  # contagem da 'atividadeX'

for atividade, contagem in contador.most_common()r:  # checar
    print(f'{atividade}: {contagem}')
Blotosmetek commented 1 year ago

How about this:

with open('atividades.txt', 'r') as arquivo:
    atividades = (atividade.strip() for atividade in arquivo)
    novas_atividades = [ atividade for atividade in atividades if atividade != '' ]

from collections import Counter

and the rest stays as you wrote it…? (yes, I am a fan of generators and list comprehensions)

villares commented 1 year ago

Yeah! Thanks, that could be nice. I think at this point the students might have seen my page about comprehensions! Maybe I should add the .strip() to the filter condition too, otherwise some space filled lines might get through.

villares commented 5 months ago

acrescentei na página sobre dicionários!