Collections Counter In Python Code Example


Example 1: collections.counter in python

>>> from collections import Counter >>>  >>> myList = [1,1,2,3,4,5,3,2,3,4,2,1,2,3] >>> print Counter(myList) Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1}) >>> >>> print Counter(myList).items() [(1, 3), (2, 4), (3, 4), (4, 2), (5, 1)] >>>  >>> print Counter(myList).keys() [1, 2, 3, 4, 5] >>>  >>> print Counter(myList).values() [3, 4, 4, 2, 1]

Example 2: collections counter

# importing the collections module import collections # intializing the arr arr = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3] # getting the elements frequencies using Counter class elements_count = collections.Counter(arr) # printing the element and the frequency for key, value in elements_count.items():    print(f"{key}: {value}")

Example 3: 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)]

Example 4: python counting dictionary

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

Example 5: python collections to dictionary

list = ["a","c","c","a","b","a","a","b","c"] cnt = Counter(list) od = OrderedDict(cnt.most_common()) for key, value in od.items():     print(key, value)

Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?