collections:容器数据类型
__all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList', 'UserString', 'Counter', 'OrderedDict', 'ChainMap']
Counter计数器
print(collections.Counter(['a', 'b', 'a', 'c', 'b', 'b'])) print(collections.Counter({'a': 2, 'b': 3, 'c': 1})) print(collections.Counter('abbabc')) print(collections.Counter(a=2, b=3, c=1)) c = collections.Counter() c.update({'a': 2, 'b': 3}) print(c) """ Counter({'b': 3, 'a': 2, 'c': 1}) Counter({'b': 3, 'a': 2, 'c': 1}) Counter({'b': 3, 'a': 2, 'c': 1}) Counter({'b': 3, 'a': 2, 'c': 1}) Counter({'b': 3, 'a': 2}) """
elements() 返回一个迭代器,生成Counter的所有元素
c = collections.Counter('exareedsassagdsfgs') c['z'] = 0 print(c) print(list(c.elements())) """ Counter({'s': 5, 'e': 3, 'a': 3, 'd': 2, 'g': 2, 'x': 1, 'r': 1, 'f': 1, 'z': 0}) ['e', 'e', 'e', 'x', 'a', 'a', 'a', 'r', 'd', 'd', 's', 's', 's', 's', 's', 'g', 'g', 'f'] """
most_common(3)出现次数最多的3个字母
for letter, count in c.most_common(3): print('%s: %7d' % (letter, count)) """ s: 5 e: 3 a: 3 """
c1 = collections.Counter('aabbdddeeee') c2 = collections.Counter('aaabbbcccddd') print(c1 + c2) print(c1 - c2) print(c1 & c2) print(c1 | c2) """ Counter({'d': 6, 'a': 5, 'b': 5, 'e': 4, 'c': 3}) Counter({'e': 4}) Counter({'d': 3, 'a': 2, 'b': 2}) Counter({'e': 4, 'a': 3, 'b': 3, 'd': 3, 'c': 3}) """
defaultdict 提前指定默认值
def default_factory(): return 'default value' d = collections.defaultdict(default_factory, foo='bar') print('d:', d) print('foo =>', d['foo']) print('bar =>', d['bar']) """ d: defaultdict(<function default_factory at 0x0000020D79EF3E18>, {'foo': 'bar'}) foo => bar bar => default value """
deque 双端队列, 支持list的一些操作
d = collections.deque('abcdefg') print(d) print(len(d)) print(d[0]) print(d[-1]) d.remove('c') print(d) """ deque(['a', 'b', 'c', 'd', 'e', 'f', 'g']) 7 a g deque(['a', 'b', 'd', 'e', 'f', 'g']) """
左右添加
d1 = collections.deque() d1.extend('abcdefg') print(d1) d1.append('h') print(d1) d2 = collections.deque() d2.extendleft(range(6)) print(d2) d2.appendleft(6) print(d2) """ deque(['a', 'b', 'c', 'd', 'e', 'f', 'g']) deque(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']) deque([5, 4, 3, 2, 1, 0]) deque([6, 5, 4, 3, 2, 1, 0]) """
取出
d = collections.deque('abcdefg') print(d.pop()) print(d.popleft()) """ g a """
旋转
d = collections.deque(range(10)) print(d) d.rotate(2) print(d) d.rotate(-2) print(d) """ deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) deque([8, 9, 0, 1, 2, 3, 4, 5, 6, 7]) deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) """
namedtuple 命名的元祖, 创建一个类,字段名重复或是关键字会报错,使用rename=True对非法字段名重命名.'_index'
Person = collections.namedtuple('Person', 'name age gender') print(type(Person)) bob = Person(name='bob', age =30, gender='male') print(bob) """ <class 'type'> Person(name='bob', age=30, gender='male') """
OrderedDict 顺序字典
记录插入的顺序,比较时比较顺序
d1 = collections.OrderedDict() d1['a'] = 'A' d1['b'] = 'B' d1['c'] = 'C' d2 = collections.OrderedDict() d2['c'] = 'C' d2['a'] = 'A' d2['b'] = 'B' print(d1 == d2) """ False """