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('jonesy@example.com', '2012-10-19')
In [44]: sub
Out[44]: Subscriber(addr='jonesy@example.com', joined='2012-10-19')
In [45]: sub.addr
Out[45]: 'jonesy@example.com'
In [46]: addr, joined = sub
In [47]: addr
Out[47]: 'jonesy@example.com'