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. 17. 星际争霸之php设计模式--职责链模式

    题记==============================================================================本php设计模式专辑来源于博客(jymo ...

  2. 《zw版·Halcon-delphi系列原创教程》 Halcon分类函数007, match,图像匹配

    <zw版·Halcon-delphi系列原创教程> Halcon分类函数007, match,图像匹配 为方便阅读,在不影响说明的前提下,笔者对函数进行了简化: :: 用符号“**”,替换 ...

  3. ubuntu 中增加鼠标右键菜单,为Windows 的exe 程序快速增加桌面快捷键

    #!/bin/bashmyfile=$NAUTILUS_SCRIPT_SELECTED_FILE_PATHSmyfilename=${myfile##*/}myfilename=${myfilenam ...

  4. XML标签

    SQL标签库提供了创建和操作XML文档的标签. 引入语法:<%@ taglib prefix="x" uri="http://java.sun.com/jsp/js ...

  5. 初识python第二天(3)

    我们接着上一篇博客,继续来来了解Python一些常见类的函数使用方法 一.int # 运算符,>=,比较self是否大于等于value,只要满足大于或者等于其中一个条件,就返回True,否则就返 ...

  6. 【转】 #1451 - Cannot delete or update a parent row: a foreign key constraint fails 问题的解决办法

    转载地址:http://blog.csdn.net/donglynn/article/details/17056099 错误 SQL 查询: DELETE FROM `zmax_lang` WHERE ...

  7. Thinkphp单字母快捷键

    在ThinkPHP中有许多使用简便的单字母函数(即快捷方法),可以很方便开发者快速的调用,但是字母函数却不方便记忆,本文将所有的字母函数总结一下,以方便以后查找. 1.U() URL组装 支持不同UR ...

  8. StudyFoxCMS-8

    1.swiper插件使用 首页图片滚动插件. (1)下载:bower install swiper (2)使用:参考中文官网(http://www.swiper.com.cn/usage/index. ...

  9. Javasocket1

    转载自http://www.cnblogs.com/linzheng/archive/2011/01/23/1942328.html java socket编程 一,网络编程中两个主要的问题 一个是如 ...

  10. JS常规的验证代码 - 手机号,邮箱,字符串查找

    //在字符串中执行查找 function isDisgit(s){ var reg = /^[0-9]{1,20}$/; var result = reg.exec(s); //如果格式不正确,返回n ...