I. Collections
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 Namedtuplepoint = Namedtuple ("point", [' X ', ' y ']) p = Point (1, 2) print P.xprint p.y
2.deque
Deque is a two-way list for efficient insert and efficient delete operations, suitable for use in queues and stacks
From collections Import Dequeq = Deque ([' A ', ' B ', ' C ']) q.append (' x ') # Add q.appendleft (' Y ') to the tail and add print Q # deque to the head ([ ' Y ', ' A ', ' B ', ' C ', ' X ']) Q.pop () # Popup element q.popleft () print Q # deque ([' A ', ' B ', ' C '])
3.defaultdict
When using Dict, if the referenced key does not exist, the keyerror is thrown. If you want to return a default value when the key does not exist, you can use Defaultdict.
Note: ordereddict keys are sorted in the order in which they are inserted, not the key itself.
From collections Import DEFAULTDICTDD = Defaultdict (lambda: ' N/a ') dd[' key1 '] = ' abc ' Print dd[' Key1 '] # Key1 exists, return ' abc ' Prin T dd[' Key2 ' # Key2 not present, return default value ' N/a '
4.OrderedDict
When using Dict, key is unordered and we cannot determine the order of key when iterating over Dict. If you want to keep the key in order, you can use Ordereddict:
From collections Import ORDEREDDICTD = Dict (' (' A ', ' 1 '), (' B ', 2), (' C ', 3)]) Print D # dict key is unordered {' A ': 1, ' C ': 3, ' B ': 2} od = ordereddict (' A ', 1), (' B ', 2), (' C ', 3)]) print OD # ordereddict key is ordered ordereddict ([' A ', ' 1 '), (' B ', 2), (' C ', 3)])
5.Counter
Counter is a simple counter, in fact it is also a subclass of Dict:
From collections Import Counterc = Counter () for CH in ' programming ': c[ch] = C[ch] + 1 print C # Counter ({' G ': 2, ' M ': 2, ' R ': 2, ' a ': 1, ' I ': 1, ' O ': 1, ' n ': 1, ' P ': 1}
Two. base64
Base64 is an arbitrary binary-to-text string encoding that is commonly used to transmit small amounts of binary data in URLs, cookies, and Web pages
Import base64print Base64.b64encode (' binary string ') # ' ymluyxj5ahn0cmluzw== ' Print Base64.b64decode (' ymluyxj5ihn0cmluzw== ') # ' binary string '
Three. struct
Four. Hashlib
Five. Itertools
Six. XML
Seven. Htmlparser
Python Learning Notes (12)-common built-in modules