|
这个模块中实现了一些类,非常灵活。可以用于替代python 内置的dict 、list 、tuple 、set 类型。并且一些功能是这些内置类型所不存在的。
在网络上找了一些资料,重点说说collections 模块中的 deque 、defaultdict、Counter 类
1、class deque
类似于python 内置的 list ,不过它是一个双向的list。可以在任意一头进行操作
help(collections.deque)
class deque(__builtin__.object)
deque([iterable[, maxlen]]) --> deque object
deque 的参数应该时一个iterable.
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
| In [1]: import collections
In [2]: d = collections.deque('abcdef')
In [3]: print d
deque(['a', 'b', 'c', 'd', 'e', 'f'])
In [4]: d.append('mm') #追加元素
In [5]: print d
deque(['a', 'b', 'c', 'd', 'e', 'f', 'mm'])
In [6]: d.appendleft('gg') #从左追加元素
In [7]: print d
deque(['gg', 'a', 'b', 'c', 'd', 'e', 'f', 'mm'])
In [8]: d.pop() # pop 一个元素
Out[8]: 'mm'
In [9]: print d
deque(['gg', 'a', 'b', 'c', 'd', 'e', 'f'])
In [10]: d.popleft() #从左pop 一个元素
Out[10]: 'gg'
In [11]: print d
deque(['a', 'b', 'c', 'd', 'e', 'f'])
In [12]: d.extend('xyz') #扩展
In [13]: print d
deque(['a', 'b', 'c', 'd', 'e', 'f', 'x', 'y', 'z'])
In [14]: d.extendleft('123') #左扩展
In [15]: print d
deque(['3', '2', '1', 'a', 'b', 'c', 'd', 'e', 'f', 'x', 'y', 'z'])
In [16]: d.reverse() #反转
In [17]: print d
deque(['z', 'y', 'x', 'f', 'e', 'd', 'c', 'b', 'a', '1', '2', '3'])
In [22]: d.extend('1111')
In [23]: d.count('1') #统计一个元素的个数
Out[23]: 5
In [24]: print d
deque(['z', 'y', 'x', 'f', 'e', 'd', 'c', 'b', 'a', '1', '2', '3', '1', '1', '1', '1'])
In [27]: d.rotate(2) #右旋转
In [28]: print d
deque(['1', '1', 'z', 'y', 'x', 'f', 'e', 'd', 'c', 'b', 'a', '1', '2', '3', '1', '1'])
In [29]: d.rotate(-2) #左旋转
In [30]: print d
deque(['z', 'y', 'x', 'f', 'e', 'd', 'c', 'b', 'a', '1', '2', '3', '1', '1', '1', '1'])
In [31]: d.clear() #清空
In [32]: print d
deque([])
|
另外在deque 函数中发现一个maxlen参数。主要是限制这个双向list 的 大小
1
2
3
4
| In [34]: d = collections.deque(xrange(10),5)
In [35]: print d
deque([5, 6, 7, 8, 9], maxlen=5)
In [36]:
|
2、class defaultdict
python 内置的dict 类型有一个setdefault 方法,这个方法的意思是。获取一个dict 中key 对应的value 。若这个key 不存在于dict 中,则在这个dict 设置 key, 这个key 对应的 value 为 defaultdict 设置的相应值
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| In [46]: d = {'Name':'God','Age':28}
In [52]: d.setdefault('Name') # 这个key 存在于dict 中,因此返回了对应的value
Out[52]: 'God'
In [48]: d.setdefault('test') # 这个key不存在于dict 中,因此它被set 到了dict中,没有指定value ,则value 为 None
In [49]: d
Out[49]: {'Age': 28, 'Name': 'God', 'test': None}
In [50]: d.setdefault('test2','test2value') # 这个key不存在于dict 中,因此它被set 到了dict中,指定value 为 "test2value"
Out[50]: 'test2value'
In [51]: d
Out[51]: {'Age': 28, 'Name': 'God', 'test': None, 'test2': 'test2value'}
|
而class defaultdict类似于dict 中的 setdefault函数. 只是它在初始化这个dict 的时候就已经设置了默认值.
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| #! /usr/bin/env python
import collections
def default_factory():
return "defualt value"
#在dict存在一个d['foo'] = 'bar' 的值。若获取不存在于dict中的key,
#则返回default_factory 函数的返回值
d = collections.defaultdict(default_factory,foo='bar')
print 'd:',d
print "foo=>",d.get('foo')
print "foo=>",d['foo']
print "var=>",d['bar']
print '*' * 20
# 定义的这个dict,若key 不存在于dict 中,则将这个key放到dict中,
# 并对这个key赋值为list
d = collections.defaultdict(list)
print 'd:',d
print "foo=>",d.get('foo')
print "foo=>",d['foo']
print "var=>",d['bar']
|
执行结果如下:
1
2
3
4
5
6
7
8
9
| d: defaultdict(<function default_factory at 0x7f230849e8c0>, {'foo': 'bar'})
foo=> bar
foo=> bar
var=> defualt value
********************
d: defaultdict(<type 'list'>, {})
foo=> None
foo=> []
var=> []
|
3、class Counter
我感觉Counter 这个类比较牛,它接受一下几种类型的参数,并返回一个dict
>>> c = Counter() # a new, empty counter
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
>>> c = Counter(a=4, b=2) # a new counter from keyword args
看看都时什么样的结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| In [1]: import collections
In [2]: c = collections.Counter()
In [3]: print c
Counter()
In [4]: c = collections.Counter('abcdefg')
In [5]: print c
Counter({'a': 1, 'c': 1, 'b': 1, 'e': 1, 'd': 1, 'g': 1, 'f': 1})
In [6]: c = collections.Counter({'a': 4, 'b': 2})
In [7]: print c
Counter({'a': 4, 'b': 2})
In [8]: c = collections.Counter(a=4, b=2)
In [9]: print c
Counter({'a': 4, 'b': 2})
|
那么这个返回的dict 到底是一个什么样的结构呢? 用它自己的原话说是这样的
Elements are stored as dictionary keys and their counts are stored as dictionary values
以下通过它本身的几个实例来看具体的使用:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| In [10]: c = collections.Counter('abcdeabcdabcaba')
In [12]: print c
Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
In [13]: c.most_common(3) # 显示出个数最多的三个元素
Out[13]: [('a', 5), ('b', 4), ('c', 3)]
In [14]: sorted(c) # 过滤排重
Out[14]: ['a', 'b', 'c', 'd', 'e']
In [17]: d = collections.Counter('simsalabim')
In [18]: c.update(d) # 将d 这个counter 更新到c 中
In [19]: print c
Counter({'a': 7, 'b': 5, 'c': 3, 'd': 2, 'i': 2, 'm': 2, 's': 2, 'e': 1, 'l': 1})
|
总之,Counter 类 所对应的实例,可以参考dict 的方法去操作。在上例中可以使用help(c) 去获得相应的帮助信息。
|
|