namedtuple namedtuple('名称', [属性list])
deque support appendleft () and popleft
Use list
as data is stored, accessed by index elements quickly, but inserting and removing elements is very slow, because list
a linear memory, when a large amount of data, efficiency is very low insertion and deletion.
deque for efficient implementation of bidirectional insertion and deletion list, and queue stack suitable for:
defaultdict
Use dict
, if the referenced Key does not exist, it will be thrown KeyError
. If you want to when the key is not present, a default value is returned , you can usedefaultdict.默认值是调用函数返回的,而函数在创建
defaultdict
对象时传入。
OrderedDict
Use dict
when, Key is disordered. Out of dict
doing iterations, we can not determine the order of Key.
If you want to keep the order Key, you can use OrderedDict
:
from collections import OrderedDict class 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(last=False) print('removee:',last) if containsKey: del self[key] print('set:',(key,value)) else: print('add:',(key,value)) OrderedDict.__setitem__(self,key,value)
ChainMap
ChainMap
It may be a group of dict
string together and form one logicaldict
. ChainMap
Itself is a dict, but to find the time, according to the order will look at the inside of dict.
When to use ChainMap
the most appropriate? For example: applications often need to pass parameters, parameters can be passed via the command line, can be passed through an environment variable, you can have default parameters. We can use ChainMap
a priority to find the parameters to achieve, which is to check the command-line arguments, if not passed, then check the environment variable, if not, use the default parameters.
Counter
Counter
It is a simple counter