ID EN
Collections

Counter

Python 3.11 🇮🇩 Bahasa Indonesia

Counter adalah subkelas dict untuk menghitung objek yang dapat di-hash. Ini adalah kumpulan tempat elemen disimpan sebagai kunci kamus dan jumlahnya disimpan sebagai nilai kamus. Hitungan diperbolehkan berupa nilai bilangan bulat apa pun termasuk hitungan nol atau negatif. Kelas Counter mirip dengan tas atau multiset dalam bahasa lain.

Syntax

PYTHON
class collections.Counter([iterable-or-mapping])

Contoh

Example 1
PYTHON
>>> c = Counter()                            a new, empty counter
>>> c = Counter('gallahad')                  a new counter from an iterable
>>> c = Counter({'red': 4, 'blue': 2})       a new counter from a mapping
>>> c = Counter(cats=4, dogs=8)              a new counter from keyword args
Example 2
PYTHON
>>> c = Counter(['eggs', 'ham'])
>>> c['bacon']                               count of a missing element is zero
0
Example 3
PYTHON
>>> c['sausage'] = 0                         counter entry with a zero count
>>> del c['sausage']                         del actually removes the entry
Example 4
PYTHON
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> sorted(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']
Example 5
PYTHON
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]

See Also

Counter dict hashable Counter KeyError dict Counter elements()