Monday 4 March 2019

Accessing Counters in Python

Once initialized, counters are accessed just like dictionaries. Also, it does not raise the Key Value error (if key is not present) instead the value’s count is shown as 0.

Example:
# Python program to demonstrate accessing of
# Counter elements
from collections import Counter
# Create a list
z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
col_count = Counter(z)
print(col_count)
col = ['blue','red','yellow','green']
# Here green is not in col_count
# so count of green will be zero
for color in col:
print (color, col_count[color])

Output:
Counter({'blue': 3, 'red': 2, 'yellow': 1})
blue 3
red 2
yellow 1
green 0

elements()
The elements() method returns an iterator that produces all of the items known to the Counter. Note : Elements with count <= 0 are not included.

Example:
# Python example to demonstrate elements() on
# Counter (gives back list)
from collections import Counter
coun = Counter(a=1, b=2, c=3)
print(coun)
print(list(coun.elements()))

Output:
Counter({'c': 3, 'b': 2, 'a': 1})
['a', 'b', 'b', 'c', 'c', 'c']

most_common() :
most_common() is used to produce a sequence of the n most frequently encountered input values and their respective counts.
# Python example to demonstrate most_elements() on
# Counter
from collections import Counter
coun = Counter(a=1, b=2, c=3, d=120, e=1, f=219)
# This prints 3 most frequent characters
for letter, count in coun.most_common(3):
print('%s: %d' % (letter, count))

Output:
f: 219
d: 120
c: 3

0 Comments:

Post a Comment

Popular Posts

Categories

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (115) C (77) C# (12) C++ (82) Course (62) Coursera (178) coursewra (1) Cybersecurity (22) data management (11) Data Science (91) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (5) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (747) Python Coding Challenge (205) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses