rwrr322 发表于 2015-5-18 13:03:27

Python 中的collections 模块

这个模块中实现了一些类,非常灵活。可以用于替代python 内置的dict 、list 、tuple 、set 类型。并且一些功能是这些内置类型所不存在的。

在网络上找了一些资料,重点说说collections 模块中的 deque 、defaultdict、Counter 类

1、class deque
类似于python 内置的 list ,不过它是一个双向的list。可以在任意一头进行操作

help(collections.deque)

class deque(__builtin__.object)
deque(]) --> 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 : import collections
In : d = collections.deque('abcdef')
In : print d
deque(['a', 'b', 'c', 'd', 'e', 'f'])

In : d.append('mm')         #追加元素
In : print d
deque(['a', 'b', 'c', 'd', 'e', 'f', 'mm'])

In : d.appendleft('gg')   #从左追加元素
In : print d
deque(['gg', 'a', 'b', 'c', 'd', 'e', 'f', 'mm'])

In : d.pop()    # pop 一个元素
Out: 'mm'
In : print d
deque(['gg', 'a', 'b', 'c', 'd', 'e', 'f'])

In : d.popleft() #从左pop 一个元素
Out: 'gg'
In : print d
deque(['a', 'b', 'c', 'd', 'e', 'f'])

In : d.extend('xyz')   #扩展
In : print d
deque(['a', 'b', 'c', 'd', 'e', 'f', 'x', 'y', 'z'])

In : d.extendleft('123')#左扩展
In : print d
deque(['3', '2', '1', 'a', 'b', 'c', 'd', 'e', 'f', 'x', 'y', 'z'])


In : d.reverse() #反转
In : print d
deque(['z', 'y', 'x', 'f', 'e', 'd', 'c', 'b', 'a', '1', '2', '3'])


In : d.extend('1111')
In : d.count('1')      #统计一个元素的个数
Out: 5
In : print d
deque(['z', 'y', 'x', 'f', 'e', 'd', 'c', 'b', 'a', '1', '2', '3', '1', '1', '1', '1'])

In : d.rotate(2)#右旋转
In : print d
deque(['1', '1', 'z', 'y', 'x', 'f', 'e', 'd', 'c', 'b', 'a', '1', '2', '3', '1', '1'])

In : d.rotate(-2) #左旋转
In : print d
deque(['z', 'y', 'x', 'f', 'e', 'd', 'c', 'b', 'a', '1', '2', '3', '1', '1', '1', '1'])

In : d.clear() #清空
In : print d
deque([])





另外在deque 函数中发现一个maxlen参数。主要是限制这个双向list 的 大小

1
2
3
4
In : d = collections.deque(xrange(10),5)
In : print d
deque(, maxlen=5)
In :





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 : d = {'Name':'God','Age':28}
In : d.setdefault('Name')   # 这个key 存在于dict 中,因此返回了对应的value
Out: 'God'

In : d.setdefault('test')   # 这个key不存在于dict 中,因此它被set 到了dict中,没有指定value ,则value 为 None

In : d
Out: {'Age': 28, 'Name': 'God', 'test': None}

In : d.setdefault('test2','test2value')# 这个key不存在于dict 中,因此它被set 到了dict中,指定value 为 "test2value"
Out: 'test2value'

In : d
Out: {'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 : import collections
In : c = collections.Counter()
In : print c
Counter()

In : c = collections.Counter('abcdefg')
In : print c
Counter({'a': 1, 'c': 1, 'b': 1, 'e': 1, 'd': 1, 'g': 1, 'f': 1})

In : c = collections.Counter({'a': 4, 'b': 2})
In : print c
Counter({'a': 4, 'b': 2})

In : c = collections.Counter(a=4, b=2)
In : 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 : c = collections.Counter('abcdeabcdabcaba')

In : print c
Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})

In : c.most_common(3)# 显示出个数最多的三个元素
Out: [('a', 5), ('b', 4), ('c', 3)]

In : sorted(c)# 过滤排重
Out: ['a', 'b', 'c', 'd', 'e']


In : d = collections.Counter('simsalabim')
In : c.update(d)# 将d 这个counter 更新到c 中
In : 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) 去获得相应的帮助信息。
页: [1]
查看完整版本: Python 中的collections 模块