10.2、collections

namedtuple   namedtuple('名称', [属性list])

 

 

 

 

deque support appendleft () and popleft

Use listas data is stored, accessed by index elements quickly, but inserting and removing elements is very slow, because lista 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 dictwhen, Key is disordered. Out of dictdoing 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

ChainMapIt may be a group of dictstring together and form one logicaldict . ChainMapItself is a dict, but to find the time, according to the order will look at the inside of dict.

When to use ChainMapthe 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 ChainMapa 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

CounterIt is a simple counter

 

Guess you like

Origin www.cnblogs.com/soberkkk/p/12655290.html