Python collections 模块用法举例

时间:2022-09-07 14:26:11
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. &lpar;转&rpar;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. Ubuntu 14&period;10 下进程实时IO监控iotop命令详解

    介绍 Linux下的IO统计工具如iostat, nmon等大多数是只能统计到per设备的读写情况, 如果你想知道每个进程是如何使用IO的就比较麻烦. iotop 是一个用来监视磁盘 I/O 使用状况 ...

  2. C&plus;&plus;中复制构造函数和赋值操作符

    先看一个例子: 定义了一个类:

  3. Mybatis源码之Statement处理器RoutingStatementHandler(三)

    RoutingStatementHandler类似路由器,在其构造函数中会根据Mapper文件中设置的StatementType来选择使用SimpleStatementHandler.Prepared ...

  4. c&sol;c&plus;&plus; 网络编程 getaddrinfo 函数

    网络编程 getaddrinfo 函数 解析网址,返回IP地址. 例子: #include <iostream> #include <string.h> #include &l ...

  5. 该错误的解决办法:Incorrect string value&colon; &&num;39&semi;&bsol;xF0&bsol;x9F&period;&period;&period;&&num;39&semi; for column &&num;39&semi;XXX&&num;39&semi; at row 1

    Incorrect string value: '\xF0\x9F...' for column 'XXX' at row 1 这个问题,原因是UTF-8编码有可能是两个.三个.四个字节.Emoji表 ...

  6. effective&lowbar;java第23条:请不要新代码中使用原生态类型

    从这条开始涉及泛型相关的点. 从JDK5开始Java新增了“泛型”新特性,例如:List<String>,在这之前则只有List不会限定类型. 如今的JDK版本中还是可以写原生类型,但这会 ...

  7. Windows下Apache服务器搭建

    Apache HTTP Server(简称Apache)是Apache软件基金会的一个开放源码的网页服务器,是世界使用排名第一的Web服务器软件,可以在大多数计算机操作系统中运行,由于其多平台和安全性 ...

  8. sqlplus&sol;rman登录报权限错误ORA-01031&sol;ORA-04005&sol;0RA-00554

    安装Weblogic误操作对Oracle用户属组进行了修改 --本地sqlplus登录报错权限问题??? [oracle@enmo admin]$ sqlplus / as sysdba SQL*Pl ...

  9. Oracle查询时15分钟划分

    select to_date(to_char(sysdate, 'yyyy-MM-dd hh24') || ':' ||               floor(to_number(to_char(s ...

  10. zabbix加入TCP连接数及状态的监控

    一 监控原理: [root@ nginx]# /bin/netstat -an|awk '/^tcp/{++S[$NF]}END{for(a in S) print a,S[a]}' TIME_WAI ...