from collections import namedtuple,deque,defaultdict,OrderedDict,Counter

"""
Explanation: python collections库
collections库是python内置的集合库，本文主要讲解以下5种数据结构的用法：

namedtuple  命名元组，是tuple的子类
deque  双向列表
defaultdict  有默认值的字典，是dict的子类
OrderedDict  key有序的字典，是dict的子类
Counter  计数器，是dict的子类

准备工作
End of explanation
"""


Point = namedtuple('Point',['x','y'])
p = Point(1,2)

print '【Output】'
print p
print p.x,p.y
print p.count,p.index
print isinstance(p,Point)
print isinstance(p,tuple)

"""
Explanation: namedtuple (python 2.6+)
用法：namedtuple('名称',[属性列表])
End of explanation
"""


lst = ['a','b','c']
dq = deque(lst)
dq.append('d')
print dq

dq.pop()

print dq

dq.appendleft('-1')

print dq

dq.popleft()

print dq

"""
Explanation: deque (python 2.4+)
适用于队列和栈，插入和删除元素很高效。
End of explanation
"""


dd = defaultdict(lambda:'N/A')
dd['key1'] = 'aa';
print dd['key1']
print dd['key2']

"""
Explanation: defaultdict (python 2.5+)
当key不存在的时候可返回一个默认值，默认值由传入的函数对象决定。
End of explanation
"""


data = [('a',1),('b',2),('c',3)]
d = dict(data)
print d

od = OrderedDict(data)
print od

"""
Explanation: OrderedDict(python 2.7+)
key值有序的字典，顺序按照插入的顺序排序。
End of explanation
"""


s = 'abcdeabcdabcaba'
c = Counter(s)
print c

print c.most_common(3)

print sorted(c)

print ''.join(sorted(c.elements()))

print c.values()

print c.elements()

"""
Explanation: Counter (python 2.7+)
用序列生成Counter对象
End of explanation
"""


d = Counter('bbb')
c.update(d)

print c.most_common()

"""
Explanation: 更新Counter对象
End of explanation
"""


d = {'a':1,'b':2,'c':3}
c = Counter(d)
print c

"""
Explanation: 用字典生成Counter对象
End of explanation
"""


d = {'a':'aa1','b':'ba1','c':'ca2'}
c = Counter(d)
print c

"""
Explanation: value值为字符串时，按照字典序排序
End of explanation
"""


