Participer au site avec un Tip
Rechercher
 

Améliorations / Corrections

Vous avez des améliorations (ou des corrections) à proposer pour ce document : je vous remerçie par avance de m'en faire part, cela m'aide à améliorer le site.

Emplacement :

Description des améliorations :

Vous êtes un professionnel et vous avez besoin d'une formation ? Calcul scientifique
avec Python
Voir le programme détaillé
Module « statistics » Python 3.13.2

Classe « Counter »

Informations générales

Héritage

builtins.object
    builtins.dict
        Counter

Définition

class Counter(builtins.dict):

help(Counter)

Dict subclass for counting hashable items.  Sometimes called a bag
or multiset.  Elements are stored as dictionary keys and their counts
are stored as dictionary values.

>>> c = Counter('abcdeabcdabcaba')  # count elements from a string

>>> c.most_common(3)                # three most common elements
[('a', 5), ('b', 4), ('c', 3)]
>>> sorted(c)                       # list all unique elements
['a', 'b', 'c', 'd', 'e']
>>> ''.join(sorted(c.elements()))   # list elements with repetitions
'aaaaabbbbcccdde'
>>> sum(c.values())                 # total of all counts
15

>>> c['a']                          # count of letter 'a'
5
>>> for elem in 'shazam':           # update counts from an iterable
...     c[elem] += 1                # by adding 1 to each element's count
>>> c['a']                          # now there are seven 'a'
7
>>> del c['b']                      # remove all 'b'
>>> c['b']                          # now there are zero 'b'
0

>>> d = Counter('simsalabim')       # make another counter
>>> c.update(d)                     # add in the second counter
>>> c['a']                          # now there are nine 'a'
9

>>> c.clear()                       # empty the counter
>>> c
Counter()

Note:  If a count is set to zero or reduced to zero, it will remain
in the counter until the entry is deleted or the counter is cleared:

>>> c = Counter('aaabbc')
>>> c['b'] -= 2                     # reduce the count of 'b' by two
>>> c.most_common()                 # 'b' is still in, but its count is zero
[('a', 3), ('c', 1), ('b', 0)]

Constructeur(s)

Signature du constructeur Description
__init__(self, iterable=None, /, **kwds) Create a new, empty Counter object. And if given, count elements [extrait de __init__.__doc__]

Liste des opérateurs

Signature de l'opérateur Description
__add__(self, other) Add counts from two counters. [extrait de __add__.__doc__]
__and__(self, other) Intersection is the minimum of corresponding counts. [extrait de __and__.__doc__]
__delitem__(self, elem) Like dict.__delitem__() but does not raise KeyError for missing values. [extrait de __delitem__.__doc__]
__eq__(self, other) True if all counts agree. Missing counts are treated as zero. [extrait de __eq__.__doc__]
__ge__(self, other) True if all counts in self are a superset of those in other. [extrait de __ge__.__doc__]
__gt__(self, other) True if all counts in self are a proper superset of those in other. [extrait de __gt__.__doc__]
__iadd__(self, other) Inplace add from another counter, keeping only positive counts. [extrait de __iadd__.__doc__]
__iand__(self, other) Inplace intersection is the minimum of corresponding counts. [extrait de __iand__.__doc__]
__ior__(self, other) Inplace union is the maximum of value from either counter. [extrait de __ior__.__doc__]
__isub__(self, other) Inplace subtract counter, but keep only results with positive counts. [extrait de __isub__.__doc__]
__le__(self, other) True if all counts in self are a subset of those in other. [extrait de __le__.__doc__]
__lt__(self, other) True if all counts in self are a proper subset of those in other. [extrait de __lt__.__doc__]
__ne__(self, other) True if any counts disagree. Missing counts are treated as zero. [extrait de __ne__.__doc__]
__neg__(self) Subtracts from an empty counter. Strips positive and zero counts, [extrait de __neg__.__doc__]
__or__(self, other) Union is the maximum of value in either of the input counters. [extrait de __or__.__doc__]
__pos__(self) Adds an empty counter, effectively stripping negative and zero counts [extrait de __pos__.__doc__]
__sub__(self, other) Subtract count, but keep only results with positive counts. [extrait de __sub__.__doc__]

Opérateurs hérités de la classe dict

__contains__, __getitem__, __ror__, __setitem__

Liste des méthodes

Toutes les méthodes Méthodes d'instance Méthodes statiques Méthodes dépréciées
Signature de la méthodeDescription
__class_getitem__(object) See PEP 585 [extrait de __class_getitem__.__doc__]
__missing__(self, key) The count of elements not in the Counter is zero. [extrait de __missing__.__doc__]
__reduce__(self)
__repr__(self)
copy(self) Return a shallow copy. [extrait de copy.__doc__]
elements(self) Iterator over elements repeating each as many times as its count. [extrait de elements.__doc__]
fromkeys(iterable, v=None)
most_common(self, n=None) List the n most common elements and their counts from the most [extrait de most_common.__doc__]
subtract(self, iterable=None, /, **kwds) Like dict.update() but subtracts counts instead of replacing them. [extrait de subtract.__doc__]
total(self) Sum of the counts [extrait de total.__doc__]
update(self, iterable=None, /, **kwds) Like dict.update() but add counts instead of replacing them. [extrait de update.__doc__]

Méthodes héritées de la classe dict

__getattribute__, __init_subclass__, __iter__, __len__, __reversed__, __sizeof__, __subclasshook__, clear, get, items, keys, pop, popitem, setdefault, values

Méthodes héritées de la classe object

__delattr__, __dir__, __format__, __getattribute__, __getstate__, __hash__, __init_subclass__, __reduce_ex__, __setattr__, __sizeof__, __str__, __subclasshook__

Vous êtes un professionnel et vous avez besoin d'une formation ? Programmation Python
Les compléments
Voir le programme détaillé