11.09 collections 模块:更多数据结构

collections 模块:更多数据结构

1import collections

计数器

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

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

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

双端队列

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

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

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

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

有序字典

字典的 key 按顺序排列:

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

带默认值的字典

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

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