Python作为一个“内置电池”的编程语言,标准库里面拥有非常多好用的模块。比如今天想给大家 介绍的 collections 就是一个非常好的例子。

1、collections模块基本介绍

我们都知道,Python拥有一些内置的数据类型,比如str, int, list, tuple, dict等, collections模块在这些内置数据类型的基础上,提供了几个额外的数据类型: 
1.namedtuple(): 生成可以使用名字来访问元素内容的tuple子类 
2.deque: 双端队列,可以快速的从另外一侧追加和推出对象 
3.Counter: 计数器,主要用来计数 
4.OrderedDict: 有序字典 
5.defaultdict: 带有默认值的字典

1.1 namedtuple()

namedtuple主要用来产生可以使用名称来访问元素的数据对象,通常用来增强代码的可读性, 在访问一些tuple类型的数据时尤其好用。

举个栗子:

# -*- coding: utf-8 -*-
"""
比如我们用户拥有一个这样的数据结构,每一个对象是拥有三个元素的tuple。
使用namedtuple方法就可以方便的通过tuple来生成可读性更高也更好用的数据结构。
"""
from collections import namedtuple
websites = [
('Sohu', 'http://www.google.com/', u'张朝阳'),
('Sina', 'http://www.sina.com.cn/', u'王志东'),
('163', 'http://www.163.com/', u'丁磊')
]
Website = namedtuple('Website', ['name', 'url', 'founder'])
for website in websites:
website = Website._make(website)
print website
print website[0], website.url
Website(name='Sohu', url='http://www.google.com/', founder=u'\u5f20\u671d\u9633')
Sohu http://www.google.com/
Website(name='Sina', url='http://www.sina.com.cn/', founder=u'\u738b\u5fd7\u4e1c')
Sina http://www.sina.com.cn/
Website(name='163', url='http://www.163.com/', founder=u'\u4e01\u78ca')
163 http://www.163.com/

1.2 deque

deque其实是 double-ended queue 的缩写,翻译过来就是双端队列,它最大的好处就是实现了从队列头部快速增加和取出对象: .popleft(), .appendleft() 。
你可能会说,原生的list也可以从头部添加和取出对象啊?就像这样:

l.insert(0, v)
l.pop(0)

但是值得注意的是,list对象的这两种用法的时间复杂度是 O(n) ,也就是说随着元素数量的增加耗时呈 线性上升。而使用deque对象则是 O(1) 的复杂度,所以当你的代码有这样的需求的时候, 一定要记得使用deque。

作为一个双端队列,deque还提供了一些其他的好用方法,比如 rotate 等。
举个栗子:

# -*- coding: utf-8 -*-
"""
下面这个是一个有趣的例子,主要使用了deque的rotate方法来实现了一个无限循环
的加载动画
"""
import sys
import time
from collections import deque
fancy_loading = deque('>--------------------')
while True:
print '\r%s' % ''.join(fancy_loading),
fancy_loading.rotate(1)
sys.stdout.flush()
time.sleep(0.08)

# Result: 
# 一个无尽循环的跑马灯 
------------->-------

1.3 Counter

计数器是一个非常常用的功能需求,collections也贴心的为你提供了这个功能。
举个栗子:

# -*- coding: utf-8 -*-
"""
下面这个例子就是使用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()
c = Counter(s)
# 获取出现频率最高的5个字符
print c.most_common(5)

# Result: 
[(' ', 54), ('e', 32), ('s', 25), ('a', 24), ('t', 24)]

1.4 OrderedDict

在Python中,dict这个数据结构由于hash的特性,是无序的,这在有的时候会给我们带来一些麻烦, 幸运的是,collections模块为我们提供了OrderedDict,当你要获得一个有序的字典对象时,用它就对了。
举个栗子:

# -*- coding: utf-8 -*-
from collections import OrderedDict
items = (
('A', 1),
('B', 2),
('C', 3)
)
regular_dict = dict(items)
ordered_dict = OrderedDict(items)
print 'Regular Dict:'
for k, v in regular_dict.items():
print k, v
print 'Ordered Dict:'
for k, v in ordered_dict.items():
print k, v

# Result: 
Regular Dict: 
A 1 
C 3 
B 2 
Ordered Dict: 
A 1 
B 2 
C 3

1.5 defaultdict

我们都知道,在使用Python原生的数据结构dict的时候,如果用 d[key] 这样的方式访问, 当指定的key不存在时,是会抛出KeyError异常的。
但是,如果使用defaultdict,只要你传入一个默认的工厂方法,那么请求一个不存在的key时, 便会调用这个工厂方法使用其结果来作为这个key的默认值。

# -*- coding: utf-8 -*-
from collections import defaultdict
members = [
# Age, name
['male', 'John'],
['male', 'Jack'],
['female', 'Lily'],
['male', 'Pony'],
['female', 'Lucy'],
]
result = defaultdict(list)
for sex, name in members:
result[sex].append(name)
print result

# Result:
defaultdict(<type 'list'>, {'male': ['John', 'Jack', 'Pony'], 'female': ['Lily', 'Lucy']})

解释:

Using list as the default_factory, it is easy to group a sequence of key-value pairs into a dictionary of lists.

When each key is encountered for the first time, it is not already in the mapping; so an entry is automatically created using the default_factory function which returns an empty list. The list.append() operation then attaches the value to the new list. When keys are encountered again, the look-up proceeds normally (returning the list for that key) and the list.append() operation adds another value to the list. This technique is simpler and faster than an equivalent technique using dict.setdefault():

d = {}
for k, v in s:
d.setdefault(k, []).append(v) d.items()

2、参考资料

上面只是非常简单的介绍了一下collections模块的主要内容,主要目的就是当你碰到适合使用 它们的场所时,能够记起并使用它们,起到事半功倍的效果。
如果要对它们有一个更全面和深入了解的话,还是建议阅读官方文档和模块源码:

https://docs.python.org/2/library/collections.html#module-collections

http://python.jobbole.com/65218/    Python中的高级数据结构

Python collections 模块用法举例的更多相关文章

  1. Python collections模块总结

    Python collections模块总结 除了我们使用的那些基础的数据结构,还有包括其它的一些模块提供的数据结构,有时甚至比基础的数据结构还要好用. collections ChainMap 这是 ...

  2. (转)python collections模块详解

    python collections模块详解 原文:http://www.cnblogs.com/dahu-daqing/p/7040490.html 1.模块简介 collections包含了一些特 ...

  3. Python——collections模块、time模块、random模块、os模块、sys模块

    1. collections模块 (1)namedtuple # (1)点的坐标 from collections import namedtuple Point = namedtuple('poin ...

  4. python collections模块

    collections模块基本介绍 collections在通用的容器dict,list,set和tuple之上提供了几个可选的数据类型 namedtuple() factory function f ...

  5. python pillow模块用法

    pillow Pillow是PIL的一个派生分支,但如今已经发展成为比PIL本身更具活力的图像处理库.pillow可以说已经取代了PIL,将其封装成python的库(pip即可安装),且支持pytho ...

  6. Python——collections模块

    collections模块 collections模块在内置数据类型(dict.list.set.tuple)的基础上,还提供了几个额外的数据类型:ChainMap.Counter.deque.def ...

  7. python collections模块详解

    参考老顽童博客,他写的很详细,例子也很容易操作和理解. 1.模块简介 collections包含了一些特殊的容器,针对Python内置的容器,例如list.dict.set和tuple,提供了另一种选 ...

  8. Python Jsonpath模块用法

    在使用Python做自动化校验的时候,经常会从Json数据中取值,所以会用到Jsonpath模块,这里做个简单的总结 1.关于jsonpath用来解析多层嵌套的json数据;JsonPath 是一种信 ...

  9. python timeit模块用法

    想测试一行代码的运行时间,在python中比较方便,可以直接使用timeit: >>> import timeit #执行命令 >>> t2 = timeit.Ti ...

随机推荐

  1. 【final】站立会议---11.28

    名称:nice! 组长:李权 成员:韩媛媛 刘芳芳 宫丽君 于淼 项目名称:约跑app 时间:11月28日 12:30 内容: 新任务的分配 1.李权分配任务 2.韩媛媛写站立会议 3.刘芳芳修改BU ...

  2. 机器学习实战-边学边读python代码(3)

    程序清单2-3 归一化特征值: def autoNorm(dataSet): /* >>> barray([[ 1., 2., 3.], [ 2., 3., 4.], [ 10., ...

  3. 创建空列表遇到的问题-RF

    正确的方法:使用Create List,后面为空即可

  4. tomcat 大并发报错 Maximum number of threads (200) created for connector with address null and port 8080

    1.INFO: Maximum number of threads (200) created for connector with address null and port 8091 说明:最大线 ...

  5. pageX,clientX,screenX,offsetX的区别

    pageX/pageY: 鼠标相对于整个页面的X/Y坐标,但IE不支持.以body元素为参考点. clientX/clientY: 鼠标在浏览器内容区域的X/Y坐标,不包含滚动条,即需要滚动条的地方不 ...

  6. 【转】Struts1.x系列教程(5):HTML标签库

    转载地址:http://www.blogjava.net/nokiaguy/archive/2009/01/archive/2009/01/archive/2009/01/archive/2009/0 ...

  7. mac上安装opencv3

    转载于:http://blog.csdn.net/sanwandoujiang/article/details/51159983 在macosx上安装opencv2 brew tap homebrew ...

  8. python学习之字符串变量

    1.字符串引用变量 name="Jasper" age=23 msg="my name is %s,my age is %s"%(name,age) print ...

  9. Android跨进程通信的四种方式

    由于android系统中应用程序之间不能共享内存.因此,在不同应用程序之间交互数据(跨进程通讯)就稍微麻烦一些.在android SDK中提供了4种用于跨进程通讯的方式.这4种方式正好对应于andro ...

  10. GITHUB使用简介

    前提:本地开通SSH服务  我是Ubuntu OS,其他OS自行查找,不难目的:利用Github的免费托管服务,创建自己的repo或者fork别人的repo.步骤:·安装客户端  安装如下两个git  ...