标签:style ret data 1.5 映射 line 模块 from ons
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 Counter Counter(a) 统计次数 Counter(a)[3] 某个值出现的次数 Counter(a).elements(2) 输出频率最高的两个 update() 相加 subtract() 相减
a = {‘x‘: 1, ‘z‘: 3 } b = {‘y‘: 2, ‘z‘: 4 ,‘a‘:55} from collections import ChainMap f = ChainMap(a,b) f[‘x‘] # 1 f[‘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‘}
form collections import UserDict class 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)] = item f=StrKeyDict() f[‘x‘] = 123 print(f) 返回: {‘f1‘: ‘ttt‘} key: x item: 123 {‘x‘: 123, ‘f1‘: ‘ttt‘}
>>> from collections import namedtuple >>> Point = namedtuple(‘Point‘, [‘x‘, ‘y‘]) >>> p = Point(11, 22) >>> p.x 11 >>> p.y 22
标签:style ret data 1.5 映射 line 模块 from ons
原文地址:http://www.cnblogs.com/hanqian/p/7152904.html