Learn the collections of Python every day.
The Collections module provides several additional data types based on the built-in data types (dict, list, set, tuple): Chainmap, Counter, deque, Defaultdict, Namedtuple and Ordereddict and so on.
Chainmap
Chainmap is a new feature of Python3, which is used to make multiple maps a new unit (the original map structure still exists, similar to the map being present in a list), which is much faster than creating a new map and adding another map with update. Chainmap can be used to simulate nested scenarios, and it is more useful in templates.
Chainmap supports all operations of the normal map, the following main features are shown:
# New Chainmap and its structurein[2]: fromCollectionsImportchainmapin[3]: M1 = {' Color ':' Red ',' user ':' Guest '}in[4]: m2 = {' name ':' Drfish ',' age ':' + '}in[5]: Chainmap = Chainmap (m1, M2) in[6]: Print (Chainmap.items ()) Itemsview (Chainmap ({' user ':' Guest ',' Color ':' Red '}, {' age ':' + ',' name ':' Drfish '}))# Get the elements in Chainmapin[7]: Print (Chainmap.get (' name ')) drfishin[8]: Print (Chainmap.get (' not '))None# Add Mapin[9]: M3 = {' Data ':' 1-6 '}in[Ten]: Chainmap = chainmap.new_child (m3) in[ One]: Print (Chainmap.items ()) Itemsview (Chainmap ({' Data ':' 1-6 '}, {' user ':' Guest ',' Color ':' Red '}, {' age ':' + ',' name ':' Drfish '}))# Parents Propertyin[ A]: Print (chainmap.parents) Chainmap ({' user ':' Guest ',' Color ':' Red '}, {' age ':' + ',' name ':' Drfish '}) in[ -]: Print (chainMap.parents.parents) Chainmap ({' age ':' + ',' name ':' Drfish '}) in[ -]: Print (chainMap.parents.parents.parents) chainmap ({})# Maps Propertiesin[ the]: chainmap.mapsout[ the]: [{' Data ':' 1-6 '}, {' Color ':' Red ',' user ':' Guest '}, {' age ':' + ',' name ':' Drfish '}]
- You can pass in multiple maps to initialize the Chainmap, which automatically joins an empty map if the argument is empty
- Gets the key if it does not exist, returns none
- The map can be added via the Net_child () method, and the new map is added in the previous
- The Parents property returns the Chainmap instance after the first map is dropped.
Counter
The counter is a simple counter that is very handy to use.
Initialization
Counter initialization supports multiple forms
In[18]from collections import CounterIn[19]c = Counter()In[20]c = Counter(‘hello‘)In[21]c = Counter({‘a‘:3,‘b‘:19})In[22]c = Counter(cats=2,dogs=1)In[23]cOut[23]Counter({‘cats‘: 2, ‘dogs‘: 1})
Counter returns 0 for non-existent elements and Del if it is to be deleted:
In[23]cOut[23]Counter({‘cats‘: 2, ‘dogs‘: 1})In[24]c[‘birds‘]Out[24]0In[25]del c[‘cats‘]In[26]cOut[26]Counter({‘dogs‘: 1})
The elements () method returns all elements, several of which return several, while the Most_common (n) method can return the number of elements with the first n of the quantity and their number:
inch[ in]: c = Counter (a=4, b=2, c=0, d=-2)inch[ -]: List (c. Elements()) out[ -]: [' A ',' A ',' A ',' A ',' B ',' B ']inch[ -]: C. most_common (1) out[ -]: [(' A ',3)]
Operations can also be performed between different counter, and the subtract () method will affect the caller after subtraction, and the & operation represents a small number of two (if only one counter exists, the result set is not) and | the operation takes a large number.
in[46]:C = Counter (a=13, b=11)in[47]:d = Counter (A=1, b=2)in[48]:C.subtract (d)in[49]:Cout[49]:Counter ({' A ': +, ' B ': 9}) in[51]: c+dout[51]: Counter ({' A ': +, ' B ': one})in[52]: c-d out[52]: Counter ({' A ': one, ' B ': 7})in[54]: c&dout[54]: Counter ({' A ': 1, ' B ': 2})in[55]: c|dout[55]: Counter ({' A ': +, ' B ': 9})
Note: When an operation is performed, the number of negative results is ignored directly.
Deque
Deque is a double-ended queue, very similar to the list, but can be added and deleted on the left side of the list:
inch[ the]: dq = deque (' Abd ')inch[ the]: DQ out[ the]: Deque ([' A ',' B ',' d '])inch[ About]: Dq.append (' 1 ')inch[ the]: Dq.appendleft ('-1 ')inch[ the]: DQ out[ the]: Deque (['-1 ',' A ',' B ',' d ',' 1 '])inch[ the]: Dq.popleft () out[ the]:'-1 'inch[ +]: Dq.extendleft ("Hello")inch[ -]: DQ out[ -]: Deque ([' O ',' l ',' l ',' E ',' h ',' A ',' B ',' d ',' 1 '])
Note the Extendleft (x) method is equivalent to flipping x after it is added to the front of the list. The Rotate method is then used to make the elements in the queue move forward or back in order:
inch[ the]: Dq=deque ("12345")inch[ the]: DQ out[ the]: Deque ([' 1 ',' 2 ',' 3 ',' 4 ',' 5 '])inch[ -]: DQ. Rotate(2)inch[ -]: DQ out[ -]: Deque ([' 4 ',' 5 ',' 1 ',' 2 ',' 3 '])inch[ the]: DQ. Rotate(-4)inch[ the]: DQ out[ the]: Deque ([' 3 ',' 4 ',' 5 ',' 1 ',' 2 '])
Defaultdict
Defaultdict adds a default factory above the normal dict, which automatically generates values for the corresponding type when the key does not exist:
In[88]from collections import defaultdictIn[89]d = defaultdict(int)In[90]d[‘a‘]Out[90]0In[91]d = defaultdict(dict)In[92]d[‘a‘]Out[92]{}
If the default factory is not added when initializing, the Keyerror error is also thrown:
In[93]: d = defaultdict()In[94]: d[‘a‘call last): d[‘a‘]KeyError:‘a‘
Namedtuple
Namedtuple is a reinforced version of the tuple, the most important role is to give the tuple each location of the value of the alias, increase the readability of the program:
In[95]from collections import namedtupleIn[96]Point = namedtuple("Point",[‘x‘,‘y‘])In[97]p = Point(1,2)In[98]p.xOut[98]1In[99]p.yOut[99]2
Because of the alias, the equivalent of forming a dictionary, namedtuple can be translated into the following to introduce the ordereddict, but also can be converted from a dictionary:
In[100]p._asdict()Out[100]OrderedDict([(‘x‘, 1), (‘y‘, 2)])In[101]d = {‘x‘:11,‘y‘:22}In[102]Point(**d)Out[102]Point(x=11, y=22)
Namedtuple also provides a way to get all the fields and modify the corresponding values:
In[108]pOut[108]Point(x=1, y=2)In[109]p._fieldsOut[109](‘x‘, ‘y‘)In[110]p._replace(x=10)Out[110]Point(x=10, y=2)
Ordereddict
Dict is unordered, but sometimes we want the dictionary to be orderly, ORDEREDDICT provides the service, and the key-value pairs in ordereddict are stored in the order they were added:
in[130]:fruit= (' Apple ', 4), (' Banana ', 3), (' Orange ', 2), (' Pear ', 1))in[131]:d = dict (fruit)in[132]:Dout[132]:{' Apple ': 4, ' banana ': 3, ' orange ': 2, ' pear ': 1}in[135]:D.popitem ()out[135]:(' Apple ', 4)in[136]:D.popitem ()out[136]:(' Orange ', 2)in[137]:D.popitem ()out[137]:(' banana ', 3)in[138]:D.popitem ()out[138]:(' pear ', 1)in[133]:od = ordereddict (fruit)in[134]:odout[134]:ordereddict (' Apple ', 4), (' Banana ', 3), (' Orange ', 2), (' Pear ', 1)])in[139]:Od.popitem ()out[139]:(' pear ', 1)in[140]:Od.popitem ()out[140]:(' Orange ', 2)in[141]:Od.popitem ()out[141]:(' banana ', 3)in[142]:Od.popitem ()out[142]:(' Apple ', 4)
Note: ordereddict in Popitem (last=true) function if last is set to False, first join first Popup
You can change the position of a key-value pair by using the Move_to_end (key, last=true) function, True when moving to the end, false to the beginning:
inch[146]: OD out[146]: Ordereddict ([(' Apple ',4), (' Banana ',3), (' Orange ',2), (' Pear ',1)])inch[147]: Od.move_to_end (' Apple ')inch[148]: OD out[148]: Ordereddict ([(' Banana ',3), (' Orange ',2), (' Pear ',1), (' Apple ',4)])inch[149]: Od.move_to_end (' Pear ',False)inch[ Max]: OD out[ Max]: Ordereddict ([(' Pear ',1), (' Banana ',3), (' Orange ',2), (' Apple ',4)])
Learn the collections of Python every day.