# This is a learning note for the Liaoche teacher Python tutorial
Collections is a python built-in collection module that provides a number of useful collection classes .
1, Namedtuple
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.
>>> from collections Import Namedtuple
>>> Point = namedtuple (' point ', [' X ', ' y ']) # namedtuple is a function. This creates a point class and defines two properties for it .
>>> p = Point (1, 2) # Create instance p
>>> p.x
1
2, Deque
deque is a two-way list for efficient insert and delete operations, suitable for use in queues and stacks
>>> from collections Import deque
>>> q = deque ([' A ', ' B ', ' C ')
>>> q.append (' x ')
>>> q.appendleft (' y ')
>>> Q
Deque ([' 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.
3, 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 the defaultdict
>>> from collections Import Defaultdict
# defalutdict is a class, which is equivalent to sending an anonymous function to the class as a method. Think about __getattr__.
# DD point to this class
>>> dd = defaultdict (lambda: ' N/a ')
>>> dd[' key1 '] = ' abc '
>>> dd[' key1 ' # Key1 exists
' ABC '
>>> dd[' Key2 '] # Key2 does not exist, returns the default value
' N/A '
4 , 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
>>> od = ordereddict (' A ', 1), (' B ', 2), (' C ', 3)])
>>> od # Ordereddict's Key Sort, is in the order of insertions
Ordereddict (' A ', 1), (' B ', 2), (' C ', 3)])
4.1 , ordereddict Implement a FIFO (FIFO) Dict When the capacity exceeds the limit, the first added Key
From collections Import Ordereddict
class Lastupdatedordereddict (ordereddict): # Create a class
def __init__ (self, capacity):
Super (lastupdatedordereddict, self). __init__ () # Calling method initialization parameters of the parent class
Self._capacity = capacity
def __setitem__ (self, Key, value):
ContainsKey = 1 if key in self else 0 # determine if key exists
if Len (self)-containskey >= self._capacity: # beyond capacity what to do
# Popitem () method functions: Randomly returns and deletes a pair of keys and values (items) in the dictionary
# Random deletion of Popitem () is based on the dict of the disorder .
Last = Self.popitem (last=false) #last =false : Advanced First out. last=true: Advanced post-out
Print (' Remove: ', last)
if ContainsKey: # re - set value to key
Del Self[key]
Print (' Set: ', (key, value))
Else: # Add a key-value pair
Print (' Add: ', (key, value))
ordereddict.__setitem__ (self, key, value) # Calling Methods
5 , Counter
Counter is a simple counter , for example, the number of occurrences of a statistical character
>>> from collections Import Counter
>>> C = Counter () # counter is actually a subclass of Dict.
>>> for ch in ' programming ':
... c[ch] = C[ch] + 1
...
>>> C
Counter ({' G ': 2, ' m ': 2, ' R ': 2, ' a ': 1, ' I ': 1, ' O ': 1, ' n ': 1, ' P ': 1})
Python Learning note __12.2 collections