collections庫是python內置的集合庫,本文主要講解如下5種數據結構的用法:python
from collections import namedtuple,deque,defaultdict,OrderedDict,Counter
用法:namedtuple('名稱',[屬性列表])數據結構
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)
【Output】 Point(x=1, y=2) 1 2 <built-in method count of Point object at 0x038B2288> <built-in method index of Point object at 0x038B2288> True True
適用於隊列和棧,插入和刪除元素很高效。app
lst = ['a','b','c'] dq = deque(lst) dq.append('d') print dq
deque(['a', 'b', 'c', 'd'])
dq.pop()
'd'
print dq
deque(['a', 'b', 'c'])
dq.appendleft('-1')
print dq
deque(['-1', 'a', 'b', 'c'])
dq.popleft()
'-1'
print dq
deque(['a', 'b', 'c'])
當key不存在的時候可返回一個默認值,默認值由傳入的函數對象決定。函數
dd = defaultdict(lambda:'N/A') dd['key1'] = 'aa'; print dd['key1'] print dd['key2']
aa N/A
key值有序的字典,順序按照插入的順序排序。ui
data = [('a',1),('b',2),('c',3)] d = dict(data) print d
{'a': 1, 'c': 3, 'b': 2}
od = OrderedDict(data) print od
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
s = 'abcdeabcdabcaba' c = Counter(s) print c
Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
print c.most_common(3)
[('a', 5), ('b', 4), ('c', 3)]
print sorted(c)
['a', 'b', 'c', 'd', 'e']
print ''.join(sorted(c.elements()))
aaaaabbbbcccdde
print c.values()
[5, 3, 4, 1, 2]
print c.elements()
<itertools.chain object at 0x039BC630>
d = Counter('bbb') c.update(d)
print c.most_common()
[('b', 7), ('a', 5), ('c', 3), ('d', 2), ('e', 1)]
d = {'a':1,'b':2,'c':3} c = Counter(d) print c
Counter({'c': 3, 'b': 2, 'a': 1})
d = {'a':'aa1','b':'ba1','c':'ca2'} c = Counter(d) print c
Counter({'c': 'ca2', 'b': 'ba1', 'a': 'aa1'})