Collections is a python built-in collection module that provides a number of useful collection classes.
Namedtuple
We know that a tuple can represent an immutable collection, for example, a two-dimensional coordinate of a point can be expressed as:
>>> p = (1, 2)
However, it is difficult to see (1, 2) that this tuple is used to represent a coordinate.
Defining a class is a fuss, and namedtuple comes in handy:
>>> from collections import namedtuple>>> point = Namedtuple ("point", [' X ', ' y ']) >>> p = Point ( 1, 2) >>> p.x1>>> p.y2
Namedtuple is a function that creates a custom tuple object, specifies the number of tuple elements, and can refer to an element of a tuple using a property rather than an index.
In this way, we can easily define a data type with namedtuple, which has the invariant of tuple and can be referenced according to the attribute, which is very convenient to use.
You can verify that the created point object is a seed class of tuple:
>>> isinstance (P, point) true>>> isinstance (p, tuple) True
Similarly, if you want to represent a circle with coordinates and radii, you can also define it with Namedtuple:
# namedtuple (' name ', [Property list]): Circle = namedtuple (' Circle ', [' X ', ' y ', ' r '])
Deque
When using the list to store data, accessing the elements by index is fast, but inserting and deleting elements is slow because list is linear and the data is large, and insertions and deletions are inefficient.
Deque is a two-way list for efficient insert and delete operations, suitable for queues and stacks:
>>> from collections import deque>>> q = deque ([' A ', ' B ', ' C ']) >>> q.append (' x ') >>> Q . Appendleft (' y ') >>> qdeque ([' Y ', ' A ', ' B ', ' C ', ' X '])
In addition to implementing the list's Append () and pop (), deque supports Appendleft () and Popleft (), which allows you to add or remove elements to the head very efficiently.
Defaultdict
When using Dict, if the referenced key does not exist, the keyerror is thrown. If you want the key to not exist, return a default value, you can use Defaultdict:
>>> from collections import defaultdict>>> dd = defaultdict (lambda: ' N/a ') >>> dd[' key1 '] = ' AB C ' >>> dd[' Key1 '] # Key1 exists ' abc ' >>> dd[' Key2 '] # Key2 does not exist, return default ' N/a '
Note The default value is returned by the calling function, and the function is passed in when the Defaultdict object is created.
In addition to returning a default value when key does not exist, Defaultdict's other behavior is exactly the same as Dict.
Ordereddict
When using Dict, key is unordered. We cannot determine the order of key when we iterate over the dict.
If you want to keep the key in order, you can use Ordereddict:
>>> from collections import ordereddict>>> d = dict ([' A ', 1 ', (' B ', 2), (' C ', 3)]) >>> D # dict The key is unordered {' A ': 1, ' C ': 3, ' B ': 2}>>> od = ordereddict ([' A ', 1 '), (' B ', 2), (' C ', 3)]) >>> OD # ordereddict The key is ordered Ordereddict (' A ', ' 1 ', (' B ', 2), (' C ', 3)])
Note that the Ordereddict keys are sorted in the order in which they were inserted, not the key itself:
>>> od = ordereddict () >>> od[' z '] = 1>>> od[' y '] = 2>>> od[' x '] = 3>>> Od.key S () # returns [' Z ', ' y ', ' X '] in the order of the inserted key
Ordereddict can implement a FIFO (first in, out) dict, deleting the first added key when the capacity exceeds the limit:
From collections import Ordereddictclass lastupdatedordereddict (ordereddict): def __init__ (self, capacity): Super (lastupdatedordereddict, self). __init__ () self._capacity = capacity def __setitem__ (self, Key, value): ContainsKey = 1 if key in self else 0 if Len (self)-containskey >= self._capacity: Last = Self.popitem (LA St=false) print ' Remove: ', last if ContainsKey: del Self[key] print ' Set: ', (key, value) else:< C12/>print ' Add: ', (key, value) ordereddict.__setitem__ (self, key, value)
Counter
Counter is a simple counter, for example, the number of statistical characters that appear:
>>> from collections import counter>>> c = Counter () >>> for ch in ' programming ': ... C[CH] = C[ch] + 1...>>> ccounter ({' G ': 2, ' m ': 2, ' R ': 2, ' a ': 1, ' I ': 1, ' O ': 1, ' n ': 1, ' P ': 1})
Counter is actually also a subclass of Dict, the above results can be seen, the characters ' G ', ' m ', ' R ' each appeared two times, the other characters appear once.
Summary
The collections module provides some useful collection classes that can be selected as needed.