原文:http://www.zlovezl.cn/articles/collections-in-python/

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

基本介绍

我们都知道,Python拥有一些内置的数据类型,比如str, int, list, tuple, dict等, collections模块在这些内置数据类型的基础上,提供了几个额外的数据类型:

  • namedtuple(): 生成可以使用名字来访问元素内容的tuple子类
  • deque: 双端队列,可以快速的从另外一侧追加和推出对象
  • Counter: 计数器,主要用来计数
  • OrderedDict: 有序字典
  • defaultdict: 带有默认值的字典

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 # Result:
Website(name='Sohu', url='http://www.google.com/', founder=u'\u5f20\u671d\u9633')
Website(name='Sina', url='http://www.sina.com.cn/', founder=u'\u738b\u5fd7\u4e1c')
Website(name='163', url='http://www.163.com/', founder=u'\u4e01\u78ca')

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: # 一个无尽循环的跑马灯
------------->-------

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)]

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

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']})

参考资料

上面只是非常简单的介绍了一下collections模块的主要内容,主要目的就是当你碰到适合使用 它们的场所时,能够记起并使用它们,起到事半功倍的效果。

如果要对它们有一个更全面和深入了解的话,还是建议阅读官方文档和模块源码。

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

不可不知的Python模块: collections的更多相关文章

  1. python模块--collections

    python的内建模块collections有几个关键的数据结构,平常在使用的时候,开发者可以直接调用,不需要自己重复制造轮子,这样可以提高开发效率. 1. deque双端队列 平常我们使用的pyth ...

  2. python模块collections中namedtuple()的理解

    Python中存储系列数据,比较常见的数据类型有list,除此之外,还有tuple数据类型.相比与list,tuple中的元素不可修改,在映射中可以当键使用.tuple元组的item只能通过index ...

  3. Python 模块collections

    1.深入理解python中的tuple的功能 基本特性 # 可迭代 name_tuple = ('0bug', '1bug', '2bug') for name in name_tuple: prin ...

  4. python模块--collections(容器数据类型)

    Counter类(dict的子类, 计数器) 方法 返回值类型 说明 __init__ Counter 传入可迭代对象, 会对对象中的值进行计数, 值为键, 计数为值 .elements() 迭代器 ...

  5. Python中collections模块

    目录 Python中collections模块 Counter defaultdict OrderedDict namedtuple deque ChainMap Python中collections ...

  6. Python之常用模块--collections模块

    认识模块 什么是模块? 常见的场景:一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 但其实import加载的模块分为四个通用类别: 1 使用python编写的 ...

  7. 【转】python模块分析之collections(六)

    [转]python模块分析之collections(六) collections是Python内建的一个集合模块,提供了许多有用的集合类. 系列文章 python模块分析之random(一) pyth ...

  8. Python的collections模块中namedtuple结构使用示例

      namedtuple顾名思义,就是名字+元组的数据结构,下面就来看一下Python的collections模块中namedtuple结构使用示例 namedtuple 就是命名的 tuple,比较 ...

  9. python常用模块collections os random sys

    Python 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和Python语句. 模块让你能够有逻辑地组织你的 Python 代码段. 把相关的代码 ...

随机推荐

  1. OpenVPN推送默认路由表

    根据官方Server配置文件:https://github.com/OpenVPN/openvpn/blob/master/sample/sample-config-files/server.conf ...

  2. 我是该学JAVA呢,还是学IOS开发呢?

    摘要: iOS就像Andriod一样,不是编程语言,而是操作系统.学iOS开发,其实学的是如何用Objective-C在苹果操作系统上进行各种应用程序的开发.就像学Andriod开发,其实是学如何用J ...

  3. 一步一步学习ASP.NET 5 (一)-基本概念和环境配置

    编者语:时代在变,在csdn开博一年就发了那么的两篇文章.不管是什么原因都认为有愧了.可是今年重心都会在这里发表一些文章,和大家谈谈.NET, 移动跨平台,云计算等热门话题.希望有更好的交流. 好吧言 ...

  4. Delphi 完全时尚手册之 Visual Style 篇 (界面不错) 转自http://blog.csdn.net/iseekcode/article/details/4733229

    这里先说说两个概念:Theme(主题)和 Visual Style .Theme 最早出现在 Microsoft Plus! for Windows 95 中,是 Windows 中 Wallpape ...

  5. IOS-plist文件DES加密

    转载请说明出处:http://www.cnblogs.com/gexun/p/3705207.html,谢谢. 这些天一直在做一个知识问答的项目,因为初赛的项目题目比较少,所以题目就写在本地的plis ...

  6. Property's synthesized getter follows Cocoa naming convention for returning

    Property's synthesized getter follows Cocoa naming convention for returning.   今天早上在整理代码的时候发现了如上警告. ...

  7. vs已停止工作

    第一步: 开始-->所有程序-->Microsoft Visual Studio 2012-->VisualStudio Tools-->VS2012 开发人员命令提示(以管理 ...

  8. URAL 1837. Isenbaev&#39;s Number (map + Dijkstra || BFS)

    1837. Isenbaev's Number Time limit: 0.5 second Memory limit: 64 MB Vladislav Isenbaev is a two-time ...

  9. centos7安装debuginfo

    转自:https://www.72zk.com/show/blog/20 查看内核版本,查找对应的内核rpm文件 [root@localhost ~]#uname -rsp Linux 3.10.0- ...

  10. 关于unity里pbr技术和材质 unity5默认shader和传统的对比

    刚开始也不知道什么是pbr (Physically Based Rendering)后来才发现这是一种新的渲染方式 与之对应的是材质是pbs(Physically Based Shader) unit ...