這個函數的意義在於建立一個容易讓人理解的元組數據結構(tuple),python
In [1]: from collections import namedtuple In [2]: name = namedtuple('name',['first','second']) In [3]: n = name("Mr","ZONT") In [4]: n.first Out[4]: 'Mr' In [5]: n.second Out[5]: 'ZONT'
name
(這個例子舉的比較挫),請看如下代碼,能更好理解.In [14]: name = namedtuple('wahaha',['first','second']) In [15]: name.__name__ Out[15]: 'wahaha'
In [18]: n = name("Mr","ZONT") In [19]: isinstance(n,name) Out[19]: True In [20]: isinstance(n,tuple) Out[20]: True
deque
是list
的進化版,能夠在兩頭添加和刪除元素,適合用於隊列和棧。數據結構
In [21]: from collections import deque In [22]: d = deque(['r', 'Z', 'O']) In [24]: d.append('N') In [25]: d.appendleft('M') #在最左側添加元素 In [26]: d Out[26]: deque(['M', 'r', 'Z', 'O', 'N']) In [27]: d.append('T') In [28]: d Out[28]: deque(['M', 'r', 'Z', 'O', 'N', 'T']) In [29]: d.pop() Out[29]: 'T' In [30]: d Out[30]: deque(['M', 'r', 'Z', 'O', 'N']) In [31]: d.popleft() #彈出左側的元素 Out[31]: 'M' In [32]: d Out[32]: deque(['r', 'Z', 'O', 'N'])
和傳統的dict
相比,當所選擇的key
不存在時,能夠返回一個默認值。app
In [33]: from collections import defaultdict In [35]: d = defaultdict(lambda:'NOKEY') In [36]: d['k'] = 1 In [37]: d['k'] Out[37]: 1 In [38]: d['d'] Out[38]: 'NOKEY'
defaultdict
裏面的參數必須是以函數形式傳入的,除了用上文的匿名函數還能夠用普通函數,如:In [39]: def test(): ....: return "hello" ....: In [41]: d = defaultdict(test) In [43]: d['l'] Out[43]: 'hello'
OrderedDict
比傳統的dict
的優越性在於,其key
是有順序的。python2.7
In [49]: o = OrderedDict([('100',0),('10',5),('X','Z')]) In [51]: o.keys() Out[51]: ['100', '10', 'X']
OrderedDict
的排序是根據輸入的key的順序進行排序。Counter
是一個簡單的計數器,可用於統計字符出現個數等。函數
In [52]: from collections import Counter In [54]: c = Counter('sdugvikbvqerhasasdasds') In [55]: c['a'] Out[55]: 3 In [56]: c['d'] Out[56]: 3 In [57]: c['s'] Out[57]: 5