collections 模块:更多数据结构¶

In [1]:

  1. import collections

计数器¶

可以使用 Counter(seq) 对序列中出现的元素个数进行统计。

例如,我们可以统计一段文本中出现的单词及其出现的次数:

In [2]:

  1. from string import punctuation
  2.  
  3. sentence = "One, two, three, one, two, tree, I come from China."
  4.  
  5. words_count = collections.Counter(sentence.translate(None, punctuation).lower().split())
  6.  
  7. print words_count
  1. Counter({'two': 2, 'one': 2, 'from': 1, 'i': 1, 'tree': 1, 'three': 1, 'china': 1, 'come': 1})

双端队列¶

双端队列支持从队头队尾出入队:

In [3]:

  1. dq = collections.deque()
  2.  
  3. for i in xrange(10):
  4. dq.append(i)
  5.  
  6. print dq
  7.  
  8. for i in xrange(10):
  9. print dq.pop(),
  10.  
  11. print
  12.  
  13. for i in xrange(10):
  14. dq.appendleft(i)
  15.  
  16. print dq
  17.  
  18. for i in xrange(10):
  19. print dq.popleft(),
  1. deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  2. 9 8 7 6 5 4 3 2 1 0
  3. deque([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
  4. 9 8 7 6 5 4 3 2 1 0

与列表相比,双端队列在队头的操作更快:

In [4]:

  1. lst = []
  2. dq = collections.deque()
  3.  
  4. %timeit -n100 lst.insert(0, 10)
  5. %timeit -n100 dq.appendleft(10)
  1. 100 loops, best of 3: 598 ns per loop
  2. 100 loops, best of 3: 291 ns per loop

有序字典¶

字典的 key 按顺序排列:

In [5]:

  1. items = (
  2. ('A', 1),
  3. ('B', 2),
  4. ('C', 3)
  5. )
  6.  
  7. regular_dict = dict(items)
  8. ordered_dict = collections.OrderedDict(items)
  9.  
  10. print 'Regular Dict:'
  11. for k, v in regular_dict.items():
  12. print k, v
  13.  
  14. print 'Ordered Dict:'
  15. for k, v in ordered_dict.items():
  16. print k, v
  1. Regular Dict:
  2. A 1
  3. C 3
  4. B 2
  5. Ordered Dict:
  6. A 1
  7. B 2
  8. C 3

带默认值的字典¶

对于 Python 自带的词典 d,当 key 不存在的时候,调用 d[key] 会报错,但是 defaultdict 可以为这样的 key 提供一个指定的默认值,我们只需要在定义时提供默认值的类型即可,如果 key 不存在返回指定类型的默认值:

In [6]:

  1. dd = collections.defaultdict(list)
  2.  
  3. print dd["foo"]
  4.  
  5. dd = collections.defaultdict(int)
  6.  
  7. print dd["foo"]
  8.  
  9. dd = collections.defaultdict(float)
  10.  
  11. print dd["foo"]
  1. []
  2. 0
  3. 0.0

原文: https://nbviewer.jupyter.org/github/lijin-THU/notes-python/blob/master/11-useful-tools/11.09-collections.ipynb