天天看點

python collections子產品collections.dequecollections.defaultdictcollections.OrderedDictcollections.Countercollections.namedtuple

collections.deque

雙端隊列,可以在隊列的兩端執行添加和彈出元素的操作

In [1]: from collections import deque

In [2]: q = deque()

In [3]: q.append(1)

In [4]: q.append(2)

In [5]: q.append(3)

In [6]: q
Out[6]: deque([1, 2, 3])

In [7]:  q.appendleft(4)

In [8]: q
Out[8]: deque([4, 1, 2, 3])

In [9]: q.pop()
Out[9]: 3

In [10]: q.popleft()
Out[10]: 4

In [11]: q
Out[11]: deque([1, 2])
           

使用 deque(maxlen=N) 構造函數會建立一個固定大小的隊列。當新的元素加入并且這個隊列已滿的時候, 最老的元素會自動被移除掉。

In [1]: from collections import deque

In [2]: q = deque(maxlen=3)

In [3]: q.append(1)

In [4]: q.append(2)

In [5]: q.append(3)

In [6]: q
Out[6]: deque([1, 2, 3])

In [7]: q.append(4)

In [8]: q
Out[8]: deque([2, 3, 4])
           

collections.defaultdict

defaultdict 會自動初始化每個 key 剛開始對應的值

In [12]: from collections import defaultdict

In [13]: d = defaultdict(list)

In [14]: d['a'].append(1)

In [15]: d['a'].append(2)

In [16]: d['b'].append(4)

In [17]: d
Out[17]: defaultdict(list, {'a': [1, 2], 'b': [4]})
           

在普通的字典上使用setdefault() 方法可以實作同樣的效果

In [18]: d = {}

In [19]: d.setdefault('a', []).append(1)
    ...: d.setdefault('a', []).append(2)
    ...: d.setdefault('b', []).append(4)

In [20]: d
Out[20]: {'a': [1, 2], 'b': [4]}

           

collections.OrderedDict

OrderedDict類 在疊代操作的時候它會保持元素被插入時的順序

In [22]: from collections import OrderedDict

In [23]: d = OrderedDict()

In [24]: d['foo'] = 1
    ...: d['bar'] = 2
    ...: d['spam'] = 3
    ...: d['grok'] = 4


In [26]: for key in d:
            print(key, d[key])
foo 1
bar 2
spam 3
grok 4
           

collections.Counter

将元素數量統計,然後計數傳回一個字典,鍵為元素,值為元素個數

most_common() 可以擷取出現次數最多的n個元素和對應次數

In [32]: words = [
    ...: 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
    ...: 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
    ...: 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
    ...: 'my', 'eyes', "you're", 'under'
    ...: ]

In [33]: from collections import Counter

In [34]: word_counts = Counter(words)

In [35]: top_three = word_counts.most_common(3)

In [36]: print(top_three)
[('eyes', 8), ('the', 5), ('look', 4)]
           

update方法可以繼續添加元素,然後統計

In [37]: morewords = ['why','are','you','not','looking','in','my','eyes']

In [38]: word_counts.update(morewords)

In [39]: top_three = word_counts.most_common(3)

In [40]: print(top_three)
[('eyes', 9), ('the', 5), ('look', 4)]
           

collections.namedtuple

命名元組

In [41]: from collections import namedtuple

In [42]: Subscriber = namedtuple('Subscriber', ['addr', 'joined'])

In [43]: sub = Subscriber('[email protected]', '2012-10-19')

In [44]: sub
Out[44]: Subscriber(addr='[email protected]', joined='2012-10-19')

In [45]: sub.addr
Out[45]: '[email protected]'

In [46]: addr, joined = sub

In [47]: addr
Out[47]: '[email protected]'
           

繼續閱讀