:PROPERTIES:
:ID:       4ef76164-0e67-410a-8d26-b03071a0cc41
:mtime:    20211230160701
:ctime:    20211230141219
:END:
#+title: Compter la fréquence des éléments d'une liste
#+filetags: :Python:

* Méthode sans dépendance
#+BEGIN_SRC python :results output
elements = [1, 2, 3, 4, 1, 3, 46, 7, 2, 3, 5, 6, 10]
freqs = {}
visiteds = set()
for element in elements:
    if element in visiteds:
        freqs[element] = freqs[element] + 1
    else:
        freqs[element] = 1
        visiteds.add(element)

print(f"Input list is: {elements}")
print(f"Frequency of elements is: {freqs}")
#+END_SRC
#+RESULTS:
: Input list is: [1, 2, 3, 4, 1, 3, 46, 7, 2, 3, 5, 6, 10]
: Frequency of elements is: {1: 2, 2: 2, 3: 3, 4: 1, 46: 1, 7: 1, 5: 1, 6: 1, 10: 1}

* Methode basée sur le package /collections/
#+BEGIN_SRC python :results output
import collections

elements = [1, 2, 3, 4, 1, 3, 46, 7, 2, 3, 5, 6, 10]
counter = collections.Counter(elements)

print(f"Input list is: {elements}")
print(f"Frequency of elements is: {dict(counter)}")
#+END_SRC
#+RESULTS: 
: Input list is: [1, 2, 3, 4, 1, 3, 46, 7, 2, 3, 5, 6, 10]
: Frequency of elements is: {1: 2, 2: 2, 3: 3, 4: 1, 46: 1, 7: 1, 5: 1, 6: 1, 10: 1}
