标签:一个 soft lis 默认 def code order ict size
>>> from collections import namedtuple >>> Point = namedtuple(‘Point‘, [‘x‘, ‘y‘]) >>> p = Point(1, 2) >>> p.x 1 >>> p.y 2
>>> from collections import deque >>> q = deque([‘a‘, ‘b‘, ‘c‘]) >>> q.append(‘x‘) >>> q.appendleft(‘y‘) >>> q deque([‘y‘, ‘a‘, ‘b‘, ‘c‘, ‘x‘])
c = Counter(‘abcdeabcdabcaba‘) print c 输出:Counter({‘a‘: 5, ‘b‘: 4, ‘c‘: 3, ‘d‘: 2, ‘e‘: 1})
>>> from collections import OrderedDict >>> d = dict([(‘a‘, 1), (‘b‘, 2), (‘c‘, 3)]) >>> d # dict的Key是无序的 {‘a‘: 1, ‘c‘: 3, ‘b‘: 2} >>> od = OrderedDict([(‘a‘, 1), (‘b‘, 2), (‘c‘, 3)]) >>> od # OrderedDict的Key是有序的 OrderedDict([(‘a‘, 1), (‘b‘, 2), (‘c‘, 3)]) # 注意,OrderedDict的Key会按照插入的顺序排列,不是Key本身排序: >>> od = OrderedDict() >>> od[‘z‘] = 1 >>> od[‘y‘] = 2 >>> od[‘x‘] = 3 >>> od.keys() # 按照插入的Key的顺序返回 [‘z‘, ‘y‘, ‘x‘]
from collections import defaultdict values = [11, 22, 33,44,55,66,77,88,99,90] my_dict = defaultdict(list) for value in values: if value>66: my_dict[‘k1‘].append(value) else: my_dict[‘k2‘].append(value)
# 使用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值,就可以用defaultdict: >>> from collections import defaultdict >>> dd = defaultdict(lambda: ‘N/A‘) >>> dd[‘key1‘] = ‘abc‘ >>> dd[‘key1‘] # key1存在 ‘abc‘ >>> dd[‘key2‘] # key2不存在,返回默认值 ‘N/A‘
标签:一个 soft lis 默认 def code order ict size
原文地址:http://www.cnblogs.com/wangyuanming/p/7511440.html