CKTIS / Python
collections.Counter
Conta le occorrenze di elementi utilizzabili come chiavi oppure inizializza i conteggi da un mapping.
Versione: Python 3.14; repository image, production runtime not attested
Sintassi
collections.Counter()
collections.Counter(iterable_or_mapping, /, **counts)
collections.Counter(**counts)Conta le occorrenze di elementi utilizzabili come chiavi oppure inizializza i conteggi da un mapping.
Un conteggio può valere 0.5, mentre elements() richiede interi. Una chiave assente letta con le parentesi quadre dà zero senza creare una voce. subtract mantiene i conteggi negativi e assegnare zero lascia la chiave nel contatore.
Nell’esempio a compare tre volte, sottrarre due c dà -2 e la chiave assente z dà 0.
from collections import Counter
c = Counter({"a": 1, "b": 0})
assert c["missing"] == 0 and "missing" not in c
c.subtract("aa")
assert c["a"] == -1 and list(c.elements()) == []
assert "b" in c
assert Counter(a=0.5)["a"] == 0.5 and not Counter()
Esempi
import collections
counts = collections.Counter("ababa")
counts.subtract("cc")
print(counts["a"], counts["c"], counts["z"])
Risultato
3 -2 0
Nell’esempio a compare tre volte, sottrarre due c dà -2 e la chiave assente z dà 0.