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. 企业信息系统——CRM

    客户关系管理系统(Customer Relationship Management)将客户看作是企业的一项重要资产,客户关怀是CRM的中心,其目的是与客户建立长期和有效的业务关系,在与客户的每个“接触 ...

  2. textarea 多行文本保存数据到DB,取出后恢复换行

    Steps: 1.保存到数据库之前把textarea中的换行字符转换为<br>. var dbStr = textareaStr.replace(/\n|\r\n/g,"< ...

  3. [转]Git调用第三方对比工具beyondCompare

    点击阅读原文 对于我这种 git 命令行小白来说, git 自带的对比工具各种水土不服,想念以前的 svn 小乌龟 + beyondCompare 的日子...纠结完 gitHub client 未果 ...

  4. StringBuilder和Append的一个程序及一个基础概念

    废话少说直接来说:比如在串口数据操作中,我们只想显示串口接收的字符串,好吧你用string[]吧,有多少个字符串(顺便说下二进制在C#中是以字符串形式出现的)就要分配多少个储存空间,自己试下,要你你干 ...

  5. JSON 格式说明

    一维json { "sn" : "CS20160918095444121640", "suitstypes_id" : "47&q ...

  6. jQuery Validate input是动态变化的

    表单验证 $("#dataList").append("<div id='data"+dataNum+"' style='padding-top ...

  7. query判断值是否为空,针对前台提交数据的校验

    1.<input type="hidden" id="key" name="key" value="123"> ...

  8. jquery判断对象是否为空并遍历对象

    javascript : if(document.getElementById("target_obj_id")){ } else { } jquery: 因为 $("# ...

  9. 使用phantomjs操作DOM并对页面进行截图需要注意的几个问题

    phantomjs是一个无界面浏览器,可用于网页截图和前端自动化测试,基于webkit内核(也就是chrome使用的内核),并使用js编写业务脚本来请求.浏览和操作页面.最近前端监控需要用到phant ...

  10. KNN算法与Kd树

    最近邻法和k-近邻法 下面图片中只有三种豆,有三个豆是未知的种类,如何判定他们的种类? 提供一种思路,即:未知的豆离哪种豆最近就认为未知豆和该豆是同一种类.由此,我们引出最近邻算法的定义:为了判定未知 ...