#!/usr/bin/env python3 # _*_ coding:utf-8 _*_ # ======================================================== # Module : collections # Author : luting # Create Date : 2018/6/4 # Amended by : luting # Amend History : 2018/6/4 # ======================================================== # collections => python内建集合模块 # namedtuple => 创建自定义tuple对象,并规定tuple元素个数,可以使用属性来引用tuple元素 from collections import namedtuple point = namedtuple('POINT', ['X', 'Y']) p = point(1, 2) print(p.X, p.Y) # deque => 为了高效实现插入和删除操作的双向列表, 适合用于队列和栈 from collections import deque # 支持append/pop/appendleft/popleft q = deque(['a', 'b', 'c']) q.append('x') q.appendleft('y') print(q) # defaultdict => key不存在时,返回一个默认值 from collections import defaultdict dd = defaultdict(lambda: 'N/A') dd['key1'] = 'abc' print(dd['key2']) # orderdict => 保持key的顺序 from collections import OrderedDict od = OrderedDict([('a', 1), ('b', 2), ('c', 3)]) print(od, dict([('a', 1), ('b', 2), ('c', 3)])) # Counter => 是一个简单的计数器 from collections import Counter c = Counter() for ch in 'programming': c[ch] += 1 print(c)