CKTIS / Python
collections.Counter
Zählt Vorkommen hashbarer Elemente oder übernimmt Anfangswerte aus einer Abbildung.
Version: Python 3.14; repository image, production runtime not attested
Syntax
collections.Counter()
collections.Counter(iterable_or_mapping, /, **counts)
collections.Counter(**counts)Zählt Vorkommen hashbarer Elemente oder übernimmt Anfangswerte aus einer Abbildung.
Zählerstände können etwa 0.5 sein, während elements() ganzzahlige Werte verlangt. Ein fehlender Schlüssel liefert beim Zugriff mit Klammern null, ohne einen Eintrag anzulegen. subtract behält negative Zählerstände bei und eine gespeicherte Null entfernt den Schlüssel nicht.
Im Beispiel kommt a dreimal vor, zweimaliges Abziehen von c ergibt -2 und das fehlende z liefert 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()
Beispiele
import collections
counts = collections.Counter("ababa")
counts.subtract("cc")
print(counts["a"], counts["c"], counts["z"])
Ergebnis
3 -2 0
Im Beispiel kommt a dreimal vor, zweimaliges Abziehen von c ergibt -2 und das fehlende z liefert 0.