<>collections modular

This module implements the container for a specific purpose , To provide Python Standard built in containers dict,list,set,tuple Alternative options for .

* Counter: Subclasses of dictionaries , Provides the counting function of hashable objects
* defaultdict: Subclasses of dictionaries , Provides a factory function , Default values are provided for dictionary queries
* OrderedDict: Subclasses of dictionaries , It retains the order in which they were added
* namedtuple: Factory function for creating named tuple subclasses
* deque: Similar to list container , It realizes the rapid addition at both ends (append) And pop up (pop)
* ChainMap: Dictionary like container class , Assemble multiple mappings into a view
<>Counter

Counter It's a dict Subclass , It is mainly used to count the frequency of objects you visit .
>>> import collections >>> # Count the number of times a character appears ... collections.Counter('hello world')
Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1}) >>> #
Count the number of words ... collections.Counter('hello world hello lucy'.split()) Counter({
'hello': 2, 'world': 1, 'lucy': 1})
common method :

*
elements(): Returns an iterator , The number of repetitions per element , If the count of an element is less than 1, Will be ignored

*
most_common([n]): Returns a list , provide n Most frequently accessed elements and counts

*
subtract([iterable-or-mapping]): Subtracting elements from iterated objects , The input and output can be 0 Or negative

*
update([iterable-or-mapping]): Count elements from an iterated object or from another Mapping objects ( Or counter ) add to
>>> c = collections.Counter('hello world hello lucy'.split()) >>> c Counter({
'hello': 2, 'world': 1, 'lucy': 1}) >>> # Gets the number of accesses to the specified object , It can also be used get method ... c['hello']
2 >>> # View elements ... list(c.elements()) ['hello', 'hello', 'world', 'lucy'] >>> c1 =
collections.Counter('hello world'.split()) >>> c2 = collections.Counter('hello
lucy'.split()) >>> c1 Counter({'hello': 1, 'world': 1}) >>> c2 Counter({'hello':
1, 'lucy': 1}) >>> # Append object ,+ perhaps c1.update(c2) ... c1+c2 Counter({'hello': 2,
'world': 1, 'lucy': 1}) >>> # Reduce objects ,- perhaps c1.subtract(c2) ... c1-c2 Counter({'world'
: 1}) >>> # eliminate ... c.clear() >>> c Counter()
<>defaultdict

Returns a new dictionary like object . defaultdict It's built-in dict Subclass of class .

class collections.defaultdict([default_factory[, ...]])
>>> d = collections.defaultdict() >>> d defaultdict(None, {}) >>> e =
collections.defaultdict(str) >>> e defaultdict(<class 'str'>, {})
example

defaultdict A typical use of is to use one of the built-in types ( as str,int,list or dict etc. ) As default factory , These built-in types return null types when called without parameters .
>>> e = collections.defaultdict(str) >>> e defaultdict(<class 'str'>, {}) >>> e
['hello'] '' >>> e defaultdict(<class 'str'>, {'hello': ''}) >>> #
When a normal dictionary calls a nonexistent key , report errors ... e1 = {} >>> e1['hello'] Traceback (most recent call last):
File"<stdin>", line 1, in <module> KeyError: 'hello'
use int As default_factory
>>> fruit = collections.defaultdict(int) >>> fruit['apple'] = 2 >>> fruit
defaultdict(<class 'int'>, {'apple': 2}) >>> fruit['banana'] # When there is no object , return 0 0 >>>
fruit defaultdict(<class 'int'>, {'apple': 2, 'banana': 0})
use list As default_factory
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] >>
> d = collections.defaultdict(list) >>> for k,v in s: ... d[k].append(v) ... >>>
d defaultdict(<class 'list'>, {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]})
>>> d.items() dict_items([('yellow', [1, 3]), ('blue', [2, 4]), ('red', [1])])
>>> sorted(d.items()) [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
use dict As default_factory
>>> nums = collections.defaultdict(dict) >>> nums[1] = {'one':1} >>> nums
defaultdict(<class 'dict'>, {1: {'one': 1}}) >>> nums[2] {} >>> nums defaultdict
(<class 'dict'>, {1: {'one': 1}, 2: {}})
use set As default_factory
>>> types = collections.defaultdict(set) >>> types[' mobile phone '].add(' Huawei ') >>> types[
' mobile phone '].add(' millet ') >>> types[' monitor '].add('AOC') >>> types defaultdict(<class 'set'>,
{' mobile phone ': {' Huawei ', ' millet '}, ' monitor ': {'AOC'}})
<>OrderedDict

Python The order of the keys in the dictionary is arbitrary , They are not controlled by the order in which they are added .

collections.OrderedDict Class provides dictionary objects that retain the order in which they are added
>>> o = collections.OrderedDict() >>> o['k1'] = 'v1' >>> o['k3'] = 'v3' >>> o[
'k2'] = 'v2' >>> o OrderedDict([('k1', 'v1'), ('k3', 'v3'), ('k2', 'v2')])
If the key Add a new value on the , Will keep the original key Location of , And then overlay it value value .
>>> o['k1'] = 666 >>> o OrderedDict([('k1', 666), ('k3', 'v3'), ('k2', 'v2')])
>>> dict(o) {'k1': 666, 'k3': 'v3', 'k2': 'v2'}
<>namedtuple

Three methods of defining named tuple : The first argument is the constructor of the named tuple ( The following :Person1,Person2,Person3)
>>> P1 = collections.namedtuple('Person1',['name','age','height']) >>> P2 =
collections.namedtuple('Person2','name,age,height') >>> P3 = collections.
namedtuple('Person3','name age height')
Instantiate named tuples
>>> lucy = P1('lucy',23,180) >>> lucy Person1(name='lucy', age=23, height=180)
>>> jack = P2('jack',20,190) >>> jack Person2(name='jack', age=20, height=190)
>>> lucy.name # Directly through Instance name . attribute To call 'lucy' >>> lucy.age 23
<>deque

collections.deque Returns a new bidirectional queue object , Initialization from left to right ( How to use it append()), from iterable( Iteration object ) Data creation . If
iterable Not specified , The new queue is empty .
collections.deque Queues support thread safety , For add from both ends (append) Or pop it up (pop), Complexity O(1).
although list Objects also support similar operations , But the fixed length operation is optimized here (pop(0),insert(0,v)) Cost of .
If maxlen Not specified or None ,deque It can grow to any length . otherwise ,deque To the specified maximum length . Once the length of deque
It's full , When a new item is added , The same number of items pop up from the other end .

Methods supported :

* append(x): add to x To the right
* appendleft(x): add to x To the left
* clear(): Clear all elements , The length becomes 0
* copy(): Create a shallow copy
* count(x): Count the number of queues equal to x Elements of
* extend(iterable): Add on the right side of the queue iterable Elements in
* extendleft(iterable): Add to the left side of the queue iterable Elements in , notes : When adding on the left ,iterable The order of the parameters is added in reverse
* index(x[,start[,stop]]): Back to page x Elements ( from start Start the calculation , stay stop
before ). Returns the first match , If you don't find it , rise ValueError .
* insert(i,x): In position i insert x . notes : If inserted, it will result in a limit deque Over length maxlen The words of , Just one up IndexError .
* pop(): Remove the rightmost element
* popleft(): Remove the leftmost element
* remove(value): Remove the first one found value. Didn't throw it out ValueError
* reverse(): take deque Reverse permutation . return None .
* maxlen: Maximum length of queue , If there is no limit, it is None. >>> d = collections.deque(maxlen=10) >>> d deque(
[], maxlen=10) >>> d.extend('python') >>> [i.upper() for i in d] ['P', 'Y', 'T',
'H', 'O', 'N'] >>> d.append('e') >>> d.appendleft('f') >>> d.appendleft('g') >>>
d.appendleft('h') >>> d deque(['h', 'g', 'f', 'p', 'y', 't', 'h', 'o', 'n', 'e'
], maxlen=10) >>> d.appendleft('i') >>> d deque(['i', 'h', 'g', 'f', 'p', 'y',
't', 'h', 'o', 'n'], maxlen=10) >>> d.append('m') >>> d deque(['h', 'g', 'f',
'p', 'y', 't', 'h', 'o', 'n', 'm'], maxlen=10)
<>ChainMap

The background of the problem is that we have multiple dictionaries or maps , Want to merge them into a single map , Some people say it works update Merge , The problem with this is that a new data structure is created so that changes to the original dictionary are not synchronized . If you want to create a synchronous query method , have access to
ChainMap

Can be used to merge two or more dictionaries , When querying , Search from front to back . Easy to use :
>>> d1 = {'apple':1,'banana':2} >>> d2 = {'orange':2,'apple':3,'pike':1} >>>
combined1= collections.ChainMap(d1,d2) >>> combined2 = collections.ChainMap(d2,
d1) >>> combined1 ChainMap({'apple': 1, 'banana': 2}, {'orange': 2, 'apple': 3,
'pike': 1}) >>> combined2 ChainMap({'orange': 2, 'apple': 3, 'pike': 1}, {
'apple': 1, 'banana': 2}) >>> for k,v in combined1.items(): ... print(k,v) ...
orange2 apple 1 pike 1 banana 2 >>> for k,v in combined2.items(): ... print(k,v)
... apple 3 banana 2 orange 2 pike 1
One thing to note is to be right ChainMap When modifying, only the first dictionary will be modified , If the key does not exist in the first dictionary , Will be added .
>>> d1 = {'apple':1,'banana':2} >>> d2 = {'orange':2,'apple':3,'pike':1} >>> c
= collections.ChainMap(d1,d2) >>> c ChainMap({'apple': 1, 'banana': 2}, {
'orange': 2, 'apple': 3, 'pike': 1}) >>> c['apple'] 1 >>> c['apple'] = 2 >>> c
ChainMap({'apple': 2, 'banana': 2}, {'orange': 2, 'apple': 3, 'pike': 1}) >>> c[
'pike'] 1 >>> c['pike'] = 3 >>> c ChainMap({'apple': 2, 'banana': 2, 'pike': 3},
{'orange': 2, 'apple': 3, 'pike': 1})
In principle ,ChainMap
The dictionary is actually stored in a queue , When adding or deleting a dictionary, it will only be performed on the first dictionary , When searching, they will search in turn ,new_child()
Method essentially puts a dictionary before the first element of the list , The default is {}, and parents Is to remove the elements at the beginning of the list
>>> a = collections.ChainMap() >>> a['x'] = 1 >>> a ChainMap({'x': 1}) >>> b =
a.new_child() >>> b ChainMap({}, {'x': 1}) >>> b['x'] = 2 >>> b ChainMap({'x': 2
}, {'x': 1}) >>> b['y'] = 3 >>> b ChainMap({'x': 2, 'y': 3}, {'x': 1}) >>> a
ChainMap({'x': 1}) >>> c = a.new_child() >>> c ChainMap({}, {'x': 1}) >>> c['x']
= 1 >>> c['y'] = 1 >>> c ChainMap({'x': 1, 'y': 1}, {'x': 1}) >>> d = c.parents
>>> d ChainMap({'x': 1}) >>> d is a False >>> d == a True >>> a = {'x':1,'z':3}
>>> b = {'y':2,'z':4} >>> c = collections.ChainMap(a,b) >>> c ChainMap({'x': 1,
'z': 3}, {'y': 2, 'z': 4}) >>> c.maps [{'x': 1, 'z': 3}, {'y': 2, 'z': 4}] >>> c
.parents ChainMap({'y': 2, 'z': 4}) >>> c.parents.maps [{'y': 2, 'z': 4}] >>> c.
parents.parents ChainMap({}) >>> c.parents.parents.parents ChainMap({})

Technology