collections库是python内置的集合库,本文主要讲解以下5种数据结构的用法:
In [1]:
from collections import namedtuple,deque,defaultdict,OrderedDict,Counter
用法:namedtuple('名称',[属性列表])
In [2]:
Point = namedtuple('Point',['x','y'])
p = Point(1,2)
In [3]:
print '【Output】'
print p
print p.x,p.y
print p.count,p.index
print isinstance(p,Point)
print isinstance(p,tuple)
适用于队列和栈,插入和删除元素很高效。
In [4]:
lst = ['a','b','c']
dq = deque(lst)
dq.append('d')
print dq
In [6]:
dq.pop()
Out[6]:
In [7]:
print dq
In [8]:
dq.appendleft('-1')
In [9]:
print dq
In [10]:
dq.popleft()
Out[10]:
In [11]:
print dq
当key不存在的时候可返回一个默认值,默认值由传入的函数对象决定。
In [12]:
dd = defaultdict(lambda:'N/A')
dd['key1'] = 'aa';
print dd['key1']
print dd['key2']
key值有序的字典,顺序按照插入的顺序排序。
In [13]:
data = [('a',1),('b',2),('c',3)]
d = dict(data)
print d
In [15]:
od = OrderedDict(data)
print od
In [16]:
s = 'abcdeabcdabcaba'
c = Counter(s)
print c
In [17]:
print c.most_common(3)
In [18]:
print sorted(c)
In [19]:
print ''.join(sorted(c.elements()))
In [20]:
print c.values()
In [21]:
print c.elements()
In [22]:
d = Counter('bbb')
c.update(d)
In [23]:
print c.most_common()
In [24]:
d = {'a':1,'b':2,'c':3}
c = Counter(d)
print c
In [25]:
d = {'a':'aa1','b':'ba1','c':'ca2'}
c = Counter(d)
print c