“Python Counting Dictionary” Kode Jawaban

Python Counting Dictionary

counts = dict()
for i in items:
  counts[i] = counts.get(i, 0) + 1
Protelr

Python memesan

>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}

>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
rebellion

Counter Most_common

most_common([n])¶
Return a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter.
Elements with equal counts are ordered arbitrarily:

>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]
Cruel Cheetah

Jawaban yang mirip dengan “Python Counting Dictionary”

Pertanyaan yang mirip dengan “Python Counting Dictionary”

Lebih banyak jawaban terkait untuk “Python Counting Dictionary” di Python

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya