首页 > 代码库 > collectons模块

collectons模块

 

 

Counter计数

 

a=[1,2,3,2,4,4,3,5,3,5,4,6,4,5,3,5,35,2,3,5,3] from collections import CounterCounter(a)                      统计次数Counter(a)[3]                   某个值出现的次数Counter(a).elements(2)          输出频率最高的两个update()                        相加subtract()                      相减                 

 

 

 

 

 

ChainMap映射多个字典

a = {x: 1, z: 3 }b = {y: 2, z: 4 ,a:55}from collections import ChainMapf = ChainMap(a,b)f[x] # 1f[y] # 2 a中没找到,在b中找f[z] # 3 找到就不找了f[y] = yyy # a新增一个键值对,{‘x‘: 1, ‘z‘: 3, ‘y‘: ‘yyy‘}f[d] = rrr # a新增一个键值对,{‘x‘: 1, ‘z‘: 3, ‘d‘: ‘ddd‘, ‘y‘: ‘yyy‘}

 

 

 

UserDict重写字典

form collections import UserDictclass StrKeyDict(UserDict):    def __missing__(self, key):        if isinstance(key, str):            raise KeyError(key)        return self[str(key)]  # 调用__getitem__方法    def __contains__(self, key):        print(contions)        return str(key) in self.data    def __setitem__(self, key, item):        """当key不存在时,调用__missing__方法"""        self.data[f1] = ttt        print(self.data)        print("key:",key)        print("item:",item)        if key not in self.data:            self.data[str(key)] = itemf=StrKeyDict()f[x] = 123print(f)返回:{f1: ttt}key: xitem: 123{x: 123, f1: ttt}

 

 

 

namedtuple 命名元组

namedtuple是一个函数,用来创建一个自定义的tuple对象,规定了tuple元素的个数,可以用属性来引用tuple的某个元素。
>>> from collections import namedtuple>>> Point = namedtuple(Point, [x, y])>>> p = Point(11, 22)>>> p.x11>>> p.y22

 

collectons模块