文章来源:http://www.jb51.net/article/48771.htmhtml
(http://www.cnblogs.com/wushank/p/5122786.html)python
修改人:天马流行拳web
时间:2016/6/22算法
Collections模块基本介绍数据结构
咱们都知道,Python拥有一些内置的数据类型,好比str, int, list, tuple, dict等, collections模块在这些内置数据类型的基础上,提供了几个额外的数据类型:app
1.namedtuple(): 生成可使用名字来访问元素内容的tuple子类
2.deque: 双端队列,能够快速的从另一侧追加和推出对象
3.Counter: 计数器,主要用来计数
4.OrderedDict: 有序字典
5.defaultdict: 带有默认值的字典python2.7
一、可命名元组(namedtuple)
ide
# 做用:namedtuple主要用来产生可使用名称来访问元素的数据对象,一般用来加强代码的可读性, 在访问一些tuple类型的数据时尤为好用。函数
建立一个本身的可扩展tuple的类(包含tuple全部功能以及其余功能的类型),在根据类建立对象,而后调用对象post
最长用于坐标,普通的元组相似于列表以index编号来访问,而自定义可扩展的能够相似于字典的keys进行访问
下例列举用collections.namedtuple以及普通元组进行元素调用的实例子。
实例1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
【collections方法】
import
collections
#导入collections模块
mytuple
=
collections.namedtuple(
'mytuple'
,[
'x'
,
'y'
,
'z'
])
#调用namedtuple方法来定义mytuple的变量,并建立一个名称为['x','y','z']的列表。
a
=
mytuple(
3
,
5
,
7
)
#给mytuple赋值,这里赋值的(3,5,7)是分别赋值给['x','y','z']这个列表中每一个元素的。
print
(a)
>>>mytuple(x
=
3
, y
=
5
, z
=
7
)
#打印结果能够看出赋值的每一个值已经传给了列表中对应的每一个元素中了。
print
(a.x)
#上述咱们把mytuple赋给了变量a,因此a=mytuple。那么咱们在调用mytuple中的元素时,要使用a.x,a.y,a.z的方式去调用。
>>>
3
print
(a.x
*
a.z)
#a.x=3,a.z=7那么再相乘结果为21
>>>
21
|
【普通tuple调用方法】
1
2
3
4
5
6
7
8
|
mytuple
=
(
3
,
5
,
7
)
#生成一个普通的数字元组
print
(mytuple)
>>>(
3
,
5
,
7
)
print
(mytuple[
0
]
*
mytuple[
2
])
#在作元素调用以及算法计算时,由于元组调用元素跟列表同样是经过index编号来访问的因此要取出每一个元素必须使用坐标,而后再作计算。
>>>
21
|
总结:经过上述方法能够看出使用collections模块中的namedtuple方法能够给每一个元素起别名,经过名称调用的方式来获取值使用。而普通元组的方法必须经过下标的方式来取值。
实例2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
from
collections
import
namedtuple
#经过from import的方式直接调用collections模块中namedtuple这个方法。而import collections是导入这个模块中全部的方法。这种调用在使用时必须collections.namedtuple的方式来使用。
websites
=
[
(
'Sohu'
,
'http://www.google.com/'
, u
'liupeng'
),
(
'Sina'
,
'http://www.sina.com.cn/'
, u
'tony'
),
(
'163'
,
'http://www.163.com/'
, u
'jack'
)
]
#假设咱们有一个列表,列表中有三个元组,每一个元组中的元素都是不一样格式的字符串
Website
=
namedtuple(
'Website_list'
, [
'name'
,
'url'
,
'founder'
])
#经过调用namedtuple,来设置一个列表'Website_list'是这个列表的别名.而['name','url','founder']的命名是分别为了分配给大列表websites中哥哥元组中的各个元素的。
for
i
in
websites:
# for循环websites这个大列表,这里的i循环得出的结果是这个大列表中每一个元组
x
=
Website._make(i)
#从已经存在迭代对象或者序列生成一个新的命名元组。 Website是namedtuple('Website_list', ['name', 'url', 'founder'])的内容,._make(i)是websites各个元组的内容,把这两个元组重组成新的元组。
print
(x)
#x打印结果以下,生成了新的命名元组。是使用了namedtuple中._make的方法生成的。
# Result:
Website_list(name
=
'Sohu'
, url
=
'http://www.google.com/'
, founder
=
'liupeng'
)
Website_list(name
=
'Sina'
, url
=
'http://www.sina.com.cn/'
, founder
=
'tony'
)
Website_list(name
=
'163'
, url
=
'http://www.163.com/'
, founder
=
'jack'
)
|
二、队列(deque)
做用:deque实际上是 double-ended queue 的缩写,翻译过来就是双端队列,它最大的好处就是实现了从队列 头部快速增长和取出对象: .popleft(), .appendleft() 。
a = collections.deque(range(9)) #经过调用collections中deque方法来建立一个数字列表。[0,1,2,3,4,5,6,7,8] a.appendleft(4) #.appendleft(传参) 是把传的参数添加到列表的最左边。appendleft一次只支持传一个参数。 a.extend([1,2,3,4,5]) #.extend()以及append()方法是把传的参数添加到列表的最后边。而.extend(【列表,或者元组】)能够把列表中的各个元素传到列表中生成一个新的列表。 print(a.count(3)) #a.count()括号中的参数能够指定。count是查看出现的次数的。按照上例除了生成原列表中生成的数字3之外,咱们在extend列表的时候又有一个3,因此count出来的结果应该是2.说明3出现了2次。 print(a)
三、counter计数器
计数器是一个很是经常使用的功能需求,collections也贴心的为你提供了这个功能。若是counter(dict)是对字典的一个补充,若是counter(list)则是对列表的补充,初步测试对字典的值进行排序。
实例1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
a
=
collections.Counter(
'ababc'
)
#经过Counter建立a跟b两个元组,元组中的元素是以字典的方式显示的。经过字典把每一个元素重复的次数作统计分别做为字典的keys跟values.例如:Counter({'b': 2, 'a': 2, 'c': 1})
b
=
collections.Counter(
'1234abd'
)
print
(a.most_common(
3
))
# 显示n个个数。变量.most_common()中填写的位数表明从大到小取前几个数值的意思。例如是3的话,只会去3位数值[('b', 2), ('a', 2), ('c', 1)]
print
(a)
#结果为[('b', 2), ('a', 2), ('c', 1)]
a.update(b)
# 把b中的值传到a中。组合一个新的元组。(叠加)
print
(a)
#结果为Counter({'a': 3, 'b': 3, '1': 1, '4': 1, 'c': 1, 'd': 1, '3': 1, '2': 1}),由于字典是无序的因此不是按照顺序排列的。可是能够看出b中的元素已经传到了a中。
a.subtract(b)
#于.update()相反。.subtract()是表示相减。可是虽然相减了,仍然会把相减后不存在的key中的value以0的方式显示。
print
(a)
#结果为Counter({'a': 2, 'b': 2, 'c': 1, '1': 0, '4': 0, 'd': 0, '3': 0, '2': 0})
# Result:
[(
'b'
,
2
), (
'a'
,
2
), (
'c'
,
1
)]
Counter({
'b'
:
2
,
'a'
:
2
,
'c'
:
1
})
Counter({
'a'
:
3
,
'b'
:
3
,
'1'
:
1
,
'4'
:
1
,
'c'
:
1
,
'd'
:
1
,
'3'
:
1
,
'2'
:
1
})
Counter({
'a'
:
2
,
'b'
:
2
,
'c'
:
1
,
'1'
:
0
,
'4'
:
0
,
'd'
:
0
,
'3'
:
0
,
'2'
:
0
})
|
实例2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
# Result:
"""
下面这个例子就是使用Counter模块统计一段句子里面全部字符出现次数
"""
from
collections
import
Counter
s
=
'''A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.'''
.lower()
#.lower()这里指把字符串中全部的内容以小写字母呈现。(大写转小写)
print
(s)
c
=
Counter(s)
print
(c.most_common(
5
))
# 获取出现频率最高的5个字符
# Result:
a counter
is
a
dict
subclass
for
counting hashable objects. it
is
an unordered collection where elements are stored as dictionary keys
and
their counts are stored as dictionary values. counts are allowed to be
any
integer value including zero
or
negative counts. the counter
class
is
similar to bags
or
multisets
in
other languages.
[(
' '
,
54
), (
'e'
,
32
), (
's'
,
25
), (
'a'
,
24
), (
't'
,
24
)]
|
四、有序字典(orderedDict )
在Python中,dict这个数据结构因为hash的特性,是无序的,这在有的时候会给咱们带来一些麻烦, 幸运的是,collections模块为咱们提供了OrderedDict,当你要得到一个有序的字典对象时,用它就对了。
案例:
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
|
import
collections
dic
=
collections.OrderedDict()
#建立有序字典下列分别是建立有序字典中的keys跟values
dic[
'name'
]
=
'liupeng'
dic[
'Job'
]
=
'IT'
dic[
'City'
]
=
'YanTai'
print
(dic)
# Result:
OrderedDict([(
'name'
,
'liupeng'
), (
'Job'
,
'IT'
), (
'City'
,
'YanTai'
)])
#打印有序字典结果
dic[
'school'
]
=
'DaLian'
#往有序字典中添加新的Key跟value
print
(dic)
# Result:
OrderedDict([(
'name'
,
'liupeng'
), (
'Job'
,
'IT'
), (
'City'
,
'YanTai'
), (
'school'
,
'DaLian'
)])
#从打印有序字典结果中能够看出添加的key跟value已经追加到有序字典中去了
#这里就不列举无序字典例子了。有序字典最大的好处就是它有序。。。接下来你懂得。(- * -))
dic1
=
{
'name1'
:
'liupeng1'
,
'job1'
:
'IT1'
,
'city1'
:
'yantai1'
}
print
(dic1)
|
五、默认字典(defaultdict)
即为字典中的values设置一个默认类型:
defaultdict的参数默认是dict,也能够为list,tuple
实例说明1:
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
|
在使用的
dict
时,没法指定values的类型,在赋值时要进行判断,具体以下:
values
=
[
11
,
22
,
33
,
44
,
55
,
66
,
77
,
88
,
99
,
90
]
mydic
=
{}
for
v
in
values:
if
v >
66
:
if
'k1'
in
mydic:
#python2.7中有个.has_key的方法。在3.0之后版本中被废除,用in来替代。python2.7用法:if my_dict.has_key('k1')
mydic[
'k1'
].append(v)
else
:
mydic[
'k1'
]
=
[v]
else
:
if
'k2'
in
mydic:
mydic[
'k2'
].append(v)
else
:
mydic[
'k2'
]
=
[v]
print
(mydic)
# Result:
{
'k2'
: [
11
,
22
,
33
,
44
,
55
,
66
],
'k1'
: [
77
,
88
,
99
,
90
]}
而在使用了defaultdict时,代码进行了简化:
from
collections
import
defaultdict
values
=
[
11
,
22
,
33
,
44
,
55
,
66
,
77
,
88
,
99
,
90
]
my_dict
=
defaultdict(
list
)
for
v
in
values:
#v始终都是my_dict中的values,而defaultdict(list)后咱们对于keys的指定对比上例就方便不少。不用再作一层if判断了。
if
v >
66
:
my_dict[
'k1'
].append(v)
else
:
my_dict[
'k2'
].append(v)
print
(my_dict)
# Result:
defaultdict(<
class
'list'
>, {
'k1'
: [
77
,
88
,
99
,
90
],
'k2'
: [
11
,
22
,
33
,
44
,
55
,
66
]})
|
实例说明2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
from
collections
import
defaultdict
members
=
[
[
'male'
,
'John'
],
[
'male'
,
'Jack'
],
[
'female'
,
'Lily'
],
[
'male'
,
'Pony'
],
[
'female'
,
'Lucy'
],
]
result
=
defaultdict(
list
)
for
sex, name
in
members:
#这里设置2个变量做为字典(result)中的key跟value.
result[sex].append(name)
#这里把[sex]做为了字典中的key,name这个变量做为了value并append到字典result对应的key中。
print
(result)
# Result:
defaultdict(<
class
'list'
>, {
'female'
: [
'Lily'
,
'Lucy'
],
'male'
: [
'John'
,
'Jack'
,
'Pony'
]})
|
以上代码均在python3.4版本中测试过。 上面只是很是简单的介绍了一下collections模块的主要内容,主要目的就是当你碰到适合使用 它们的场所时,可以记起并使用它们,起到事半功倍的效果。 若是要对它们有一个更全面和深刻了解的话,仍是建议阅读官方文档和模块源码。 https://docs.python.org/2/library/collections.html#module-collections
“今天的努力都是明天别人对你的膜拜,今天的停滞就是明天别人对你的唾弃!“
文章来源:http://www.jb51.net/article/48771.htm
(http://www.cnblogs.com/wushank/p/5122786.html)
修改人:天马流行拳
时间:2016/6/22
Collections模块基本介绍
咱们都知道,Python拥有一些内置的数据类型,好比str, int, list, tuple, dict等, collections模块在这些内置数据类型的基础上,提供了几个额外的数据类型:
1.namedtuple(): 生成可使用名字来访问元素内容的tuple子类
2.deque: 双端队列,能够快速的从另一侧追加和推出对象
3.Counter: 计数器,主要用来计数
4.OrderedDict: 有序字典
5.defaultdict: 带有默认值的字典
一、可命名元组(namedtuple)
# 做用:namedtuple主要用来产生可使用名称来访问元素的数据对象,一般用来加强代码的可读性, 在访问一些tuple类型的数据时尤为好用。
建立一个本身的可扩展tuple的类(包含tuple全部功能以及其余功能的类型),在根据类建立对象,而后调用对象
最长用于坐标,普通的元组相似于列表以index编号来访问,而自定义可扩展的能够相似于字典的keys进行访问
下例列举用collections.namedtuple以及普通元组进行元素调用的实例子。
实例1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
【collections方法】
import
collections
#导入collections模块
mytuple
=
collections.namedtuple(
'mytuple'
,[
'x'
,
'y'
,
'z'
])
#调用namedtuple方法来定义mytuple的变量,并建立一个名称为['x','y','z']的列表。
a
=
mytuple(
3
,
5
,
7
)
#给mytuple赋值,这里赋值的(3,5,7)是分别赋值给['x','y','z']这个列表中每一个元素的。
print
(a)
>>>mytuple(x
=
3
, y
=
5
, z
=
7
)
#打印结果能够看出赋值的每一个值已经传给了列表中对应的每一个元素中了。
print
(a.x)
#上述咱们把mytuple赋给了变量a,因此a=mytuple。那么咱们在调用mytuple中的元素时,要使用a.x,a.y,a.z的方式去调用。
>>>
3
print
(a.x
*
a.z)
#a.x=3,a.z=7那么再相乘结果为21
>>>
21
|
【普通tuple调用方法】
1
2
3
4
5
6
7
8
|
mytuple
=
(
3
,
5
,
7
)
#生成一个普通的数字元组
print
(mytuple)
>>>(
3
,
5
,
7
)
print
(mytuple[
0
]
*
mytuple[
2
])
#在作元素调用以及算法计算时,由于元组调用元素跟列表同样是经过index编号来访问的因此要取出每一个元素必须使用坐标,而后再作计算。
>>>
21
|
总结:经过上述方法能够看出使用collections模块中的namedtuple方法能够给每一个元素起别名,经过名称调用的方式来获取值使用。而普通元组的方法必须经过下标的方式来取值。
实例2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
from
collections
import
namedtuple
#经过from import的方式直接调用collections模块中namedtuple这个方法。而import collections是导入这个模块中全部的方法。这种调用在使用时必须collections.namedtuple的方式来使用。
websites
=
[
(
'Sohu'
,
'http://www.google.com/'
, u
'liupeng'
),
(
'Sina'
,
'http://www.sina.com.cn/'
, u
'tony'
),
(
'163'
,
'http://www.163.com/'
, u
'jack'
)
]
#假设咱们有一个列表,列表中有三个元组,每一个元组中的元素都是不一样格式的字符串
Website
=
namedtuple(
'Website_list'
, [
'name'
,
'url'
,
'founder'
])
#经过调用namedtuple,来设置一个列表'Website_list'是这个列表的别名.而['name','url','founder']的命名是分别为了分配给大列表websites中哥哥元组中的各个元素的。
for
i
in
websites:
# for循环websites这个大列表,这里的i循环得出的结果是这个大列表中每一个元组
x
=
Website._make(i)
#从已经存在迭代对象或者序列生成一个新的命名元组。 Website是namedtuple('Website_list', ['name', 'url', 'founder'])的内容,._make(i)是websites各个元组的内容,把这两个元组重组成新的元组。
print
(x)
#x打印结果以下,生成了新的命名元组。是使用了namedtuple中._make的方法生成的。
# Result:
Website_list(name
=
'Sohu'
, url
=
'http://www.google.com/'
, founder
=
'liupeng'
)
Website_list(name
=
'Sina'
, url
=
'http://www.sina.com.cn/'
, founder
=
'tony'
)
Website_list(name
=
'163'
, url
=
'http://www.163.com/'
, founder
=
'jack'
)
|
二、队列(deque)
做用:deque实际上是 double-ended queue 的缩写,翻译过来就是双端队列,它最大的好处就是实现了从队列 头部快速增长和取出对象: .popleft(), .appendleft() 。
a = collections.deque(range(9)) #经过调用collections中deque方法来建立一个数字列表。[0,1,2,3,4,5,6,7,8] a.appendleft(4) #.appendleft(传参) 是把传的参数添加到列表的最左边。appendleft一次只支持传一个参数。 a.extend([1,2,3,4,5]) #.extend()以及append()方法是把传的参数添加到列表的最后边。而.extend(【列表,或者元组】)能够把列表中的各个元素传到列表中生成一个新的列表。 print(a.count(3)) #a.count()括号中的参数能够指定。count是查看出现的次数的。按照上例除了生成原列表中生成的数字3之外,咱们在extend列表的时候又有一个3,因此count出来的结果应该是2.说明3出现了2次。 print(a)
三、counter计数器
计数器是一个很是经常使用的功能需求,collections也贴心的为你提供了这个功能。若是counter(dict)是对字典的一个补充,若是counter(list)则是对列表的补充,初步测试对字典的值进行排序。
实例1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
a
=
collections.Counter(
'ababc'
)
#经过Counter建立a跟b两个元组,元组中的元素是以字典的方式显示的。经过字典把每一个元素重复的次数作统计分别做为字典的keys跟values.例如:Counter({'b': 2, 'a': 2, 'c': 1})
b
=
collections.Counter(
'1234abd'
)
print
(a.most_common(
3
))
# 显示n个个数。变量.most_common()中填写的位数表明从大到小取前几个数值的意思。例如是3的话,只会去3位数值[('b', 2), ('a', 2), ('c', 1)]
print
(a)
#结果为[('b', 2), ('a', 2), ('c', 1)]
a.update(b)
# 把b中的值传到a中。组合一个新的元组。(叠加)
print
(a)
#结果为Counter({'a': 3, 'b': 3, '1': 1, '4': 1, 'c': 1, 'd': 1, '3': 1, '2': 1}),由于字典是无序的因此不是按照顺序排列的。可是能够看出b中的元素已经传到了a中。
a.subtract(b)
#于.update()相反。.subtract()是表示相减。可是虽然相减了,仍然会把相减后不存在的key中的value以0的方式显示。
print
(a)
#结果为Counter({'a': 2, 'b': 2, 'c': 1, '1': 0, '4': 0, 'd': 0, '3': 0, '2': 0})
# Result:
[(
'b'
,
2
), (
'a'
,
2
), (
'c'
,
1
)]
Counter({
'b'
:
2
,
'a'
:
2
,
'c'
:
1
})
Counter({
'a'
:
3
,
'b'
:
3
,
'1'
:
1
,
'4'
:
1
,
'c'
:
1
,
'd'
:
1
,
'3'
:
1
,
'2'
:
1
})
Counter({
'a'
:
2
,
'b'
:
2
,
'c'
:
1
,
'1'
:
0
,
'4'
:
0
,
'd'
:
0
,
'3'
:
0
,
'2'
:
0
})
|
实例2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
# Result:
"""
下面这个例子就是使用Counter模块统计一段句子里面全部字符出现次数
"""
from
collections
import
Counter
s
=
'''A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.'''
.lower()
#.lower()这里指把字符串中全部的内容以小写字母呈现。(大写转小写)
print
(s)
c
=
Counter(s)
print
(c.most_common(
5
))
# 获取出现频率最高的5个字符
# Result:
a counter
is
a
dict
subclass
for
counting hashable objects. it
is
an unordered collection where elements are stored as dictionary keys
and
their counts are stored as dictionary values. counts are allowed to be
any
integer value including zero
or
negative counts. the counter
class
is
similar to bags
or
multisets
in
other languages.
[(
' '
,
54
), (
'e'
,
32
), (
's'
,
25
), (
'a'
,
24
), (
't'
,
24
)]
|
四、有序字典(orderedDict )
在Python中,dict这个数据结构因为hash的特性,是无序的,这在有的时候会给咱们带来一些麻烦, 幸运的是,collections模块为咱们提供了OrderedDict,当你要得到一个有序的字典对象时,用它就对了。
案例:
1
2
3
4
5
6
7
8
9
10
11
|