$python collections庫

collections庫是python內置的集合庫,本文主要講解如下5種數據結構的用法:python

  • namedtuple 命名元組,是tuple的子類
  • deque 雙向列表
  • defaultdict 有默認值的字典,是dict的子類
  • OrderedDict key有序的字典,是dict的子類
  • Counter 計數器,是dict的子類

準備工做

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

namedtuple (python 2.6+)

用法: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

deque (python 2.4+)

適用於隊列和棧,插入和刪除元素很高效。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'])

defaultdict (python 2.5+)

當key不存在的時候可返回一個默認值,默認值由傳入的函數對象決定。函數

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

OrderedDict(python 2.7+)

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)])

Counter (python 2.7+)

用序列生成Counter對象

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>

更新Counter對象

d = Counter('bbb')
c.update(d)
print c.most_common()
[('b', 7), ('a', 5), ('c', 3), ('d', 2), ('e', 1)]

用字典生成Counter對象

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

value值爲字符串時,按照字典序排序

d = {'a':'aa1','b':'ba1','c':'ca2'}
c = Counter(d)
print c
Counter({'c': 'ca2', 'b': 'ba1', 'a': 'aa1'})
相關文章
相關標籤/搜索