Python collections module

  1. Counter

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

1.1 Method --elements ()

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']

1.2 Method --most_common (n)

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)]

1.3 Method --subtraction (other_cnt)

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})

1.4 Method --update (other_cnt)

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})
  1. namedtuple

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

2.1 Method --_ make ()

_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')

2.2 Method --_ asdict ()

_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

2.3 Method --_ replace ()

_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')

2.4 Attribute --_ fields

_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)
  1. defaultdict

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

Python collections module
Python module import
Python module (Python learning memo ④)
Create a Python module
python original module import
Try using the collections module (ChainMap) of python3
Sort Python module imports alphabetically
How Python module import works
[Python] ModuleNotFoundError: No module named'urlparse'
Python
About the Python module venv
Automatic update of Python module
Python> dictionary / collections> defaultdict () / Counter ()
Ruby, Python Module Installation Guide
Python debug and test module
[Python] logging in your own module
A brief summary of Python collections
Cooperation between python module and API
[Code] Module and Python version output
Use blender as a python module
Python3 socket module and socket communication flow
Python unittest module execution in vs2017
Python My Number verification module released
Try using the Python Cmd module
Python executable file conversion module comparison 2
Looking for location for mercurial python module
Master the weakref module in Python
kafka python
Python Summary
Built-in python
Python comprehension
Python technique
Studying python
Today's python error: ModuleNotFoundError: No module named
Python 2.7 Countdown
Python FlowFishMaster
Python service
python tips
python function ①
Python basics
Python memo
[Python] How to display random numbers (random module)
ufo-> python (3)
Python comprehension
install python
python3 How to install an external module
Today's python error: ModuleNotFoundError: No module named
Pass the path of the imported python module
Python basics ④
Python Memorandum 2
python memo
Implementation module "deque" in queue and Python
Python Jinja2
Comparison of Japanese conversion module in Python3
Python increment
atCoder 173 Python
[Python] function
Python installation
python tips
Installing Python 3.4.3.
Create Python module [CarSensor API support module csapi]