Counter is a child class of dict and can count hashable objects.
For example, there are the following issues:
Count the number of each item in the ['a','b','c','c','a','a'] array and get the result with dict
How to solve without using Counter:
arr = ['a', 'b', 'c', 'c', 'a', 'a']
result_dict = {}
for item in arr:
if item in result_dict:
result_dict[item] = result_dict[item] + 1
else:
result_dict[item] = 1
print(result_dict)
#output
# {'a': 3, 'c': 2, 'b': 1}
How to solve when using Counter:
from collections import Counter
cnt = Counter(['a', 'b', 'c', 'c', 'a', 'a'])
print(cnt)
#output
# Counter({'a': 3, 'c': 2, 'b': 1})
Counter initialization is possible not only from arrays, but also from dicts and args.
#Initialize Counter with dict
a = Counter({'red': 4, 'blue': 2})
print(a)
#output
# Counter({'red': 4, 'blue': 2})
#Initialize Counter with args
b = Counter(cats=4, dogs=8)
print(b)
#output
# Counter({'dogs': 8, 'cats': 4})
The method of getting data from Counter is the same as dict, and you can get value by key. The difference is that when fetching data with a key that does not exist, Counter returns "0", while dict becomes KeyError.
a = Counter({'red': 4, 'blue': 2})
print(a['red'])
#output
# 4
print(a['green'])
#output
# 0
The return value of elements () is iterator. It should be noted that Counter does not output less than 1 data.
c = Counter(a=2, b=4, c=0, d=-2, e=1)
it = c.elements()
print(type(it))
#output
# <class 'itertools.chain'>
print(list(it))
#output
# ['a', 'a', 'b', 'b', 'b', 'b', 'e']
most_common (n) returns a list of Tuples in the form (element, number of occurrences)
arranged in order of number of occurrences. When the parameter n
is specified, n
elements with the highest number of occurrences are output, and when n
is not specified, all elements are output.
c = Counter('abracadabra')
print(c.most_common(2))
#output
# [('a', 5), ('b', 2)]
print(c.most_common())
#output
# [('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]
subtract (other_cnt) means to subtract another Counter object from the Counter object.
c = Counter(a=4, b=2, c=0, d=-2, e=10)
d = Counter(a=1, b=2, c=-3, d=4, f=3)
c.subtract(d)
print(c)
#output
# Counter({'e': 10, 'a': 3, 'c': 3, 'b': 0, 'f': -3, 'd': -6})
update (other_cnt) means to add another Counter object to the Counter object.
c = Counter(a=4, b=2, c=0, d=-2, e=10)
d = Counter(a=1, b=2, c=-3, d=4, f=3)
c.update(d)
print(c)
#output
# Counter({'e': 10, 'a': 5, 'b': 4, 'f': 3, 'd': 2, 'c': -3})
For example, ordinary Tuple stores and outputs student information. The court has no choice but to get the value by index as shown below. Such sources are perceived as poorly readable.
#Student Tuple(Name, age, gender)
stu = ('Kimi', 15, 'male')
print(stu[0]) #Output name
print(stu[1]) #Output age
print(stu[2]) #Output gender
namedtuple can generate named Tuples. You can access the values in Tuple like attributes instead of indexes.
from collections import namedtuple
Student = namedtuple('Student', 'name, age, gender')
stu = Student('Kimi', 15, 'male')
print(stu.name) #Output name
print(stu.age) #Output age
print(stu.gender) #Output gender
_make () can generate namedtuple from iterable objects such as list.
from collections import namedtuple
data = ['Kimi', 15, 'male']
Student = namedtuple('Student', 'name, age, gender')
stu = Student._make(data)
print(stu)
#output
# Student(name='Kimi', age=15, gender='male')
_asdict () returns the data in namedtuple with OrderDict.
from collections import namedtuple
Student = namedtuple('Student', 'name, age, gender')
stu = Student('Kimi', 15, 'male')
stu_dict = stu._asdict()
print(stu_dict)
#output
# OrderedDict([('name', 'Kimi'), ('age', 15), ('gender', 'male')])
print(stu_dict['name'])
#output
# Kimi
_replace () modifies the value of namedtuple and returns it as a new namedtuple object. Does not affect the original object.
from collections import namedtuple
Student = namedtuple('Student', 'name, age, gender')
stu = Student('Kimi', 15, 'male')
new_stu = stu._replace(age=16)
print(new_stu)
#output
# Student(name='Kimi', age=16, gender='male')
print(stu)
#output
# Student(name='Kimi', age=15, gender='male')
_fields can get the field name of namedtuple with Tuple.
from collections import namedtuple
Student = namedtuple('Student', 'name, age, gender')
print(Student._fields)
#output
# ('name', 'age', 'gender')
_fields are often used to create new namedtuples based on existing namedtuples. Similar to "inheritance" of a class.
from collections import namedtuple
Point2D = namedtuple('Point2D', 'x, y')
Point3D = namedtuple('Point3D', Point2D._fields + ('z',))
p = Point3D(30, 18, 90)
print(p)
#output
# Point3D(x=30, y=18, z=90)
When getting a value from a normal dict, if you use a key that doesn't exist, you get a KeyError.
my_dict = {'a': 1, 'b': 2}
print(my_dict['c'])
#output
# KeyError: 'c'
defaultdict can create a dict with default values. Returns the default value if accessed with a key that does not exist.
from collections import defaultdict
my_dict = defaultdict(lambda: 0, {'a': 1, 'b': 2})
print(my_dict['c'])
#output
# 0
Recommended Posts