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'王志东'),
('', '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='', 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:

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

python(43):collections模块的更多相关文章

  1. Python中collections模块

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

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

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

  3. python:collections模块

    Counter类 介绍:A counter tool is provided to support convenient and rapid tallies 构造:class collections. ...

  4. python之collections模块(OrderDict,defaultdict)

    前言: import collections print([name for name in dir(collections) if not name.startswith("_" ...

  5. 转载:Python中collections模块

    转载自:Python中collections模块 目录 Python中collections模块 Counter defaultdict OrderedDict namedtuple deque Ch ...

  6. python的Collections 模块

    Collections 模块 知识点 Counter 类 defaultdict 类 namedtuple 类 在这个实验我们会学习 Collections 模块.这个模块实现了一些很好的数据结构,它 ...

  7. Python中collections模块的使用

    本文将详细讲解collections模块中的所有类,和每个类中的方法,从源码和性能的角度剖析. 一个模块主要用来干嘛,有哪些类可以使用,看__init__.py就知道 '''This module i ...

  8. python 之 Collections模块

    官方文档:https://yiyibooks.cn/xx/python_352/library/collections.html 参考: https://blog.csdn.net/songfreem ...

  9. 【python】collections模块(有序字典,计数器,双向队列)

    collections模块基本介绍 我们都知道,Python拥有一些内置的数据类型,比如str, int, list, tuple, dict等, collections模块在这些内置数据类型的基础上 ...

  10. Python中Collections模块的Counter容器类使用教程

    1.collections模块 collections模块自Python 2.4版本开始被引入,包含了dict.set.list.tuple以外的一些特殊的容器类型,分别是: OrderedDict类 ...

随机推荐

  1. -webkit-line-clamp下多行文字溢出点点点...显示实例页面

    overflow : hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box ...

  2. [转载]TortoiseGit安装与使用

    原文地址:TortoiseGit安装与使用作者:了凡春秋 之前一直用SVN做项目开发,确实感觉这些版本控制工具非常实用,尤其是在一个团队开发项目的时候.最近偶然看到一个新的版本管理工具Git,它本来是 ...

  3. 更新卡片的zIndex

    问题描述 屏幕上有若干张互相重叠的卡片,用户每点击一张卡片,就要把这张卡片的移到最上面,也就是把它的zIndex置为最大值.应该如何操作每个卡片的zIndex才能实现? 实现方案一 定义一个全局变量g ...

  4. MATLAB 的 cell 大法(单元格数组)

    MATLAB 的 cell,称单元格数组 or 元胞数组:使用频率特别高,甚至比 struct 结构体还高. MATLAB文档给出的 cell 官方定义: A cell array is a coll ...

  5. 浅谈iOS中MVVM的架构设计

    MVVM就是在MVC的基础上分离出业务处理的逻辑到viewModel层. M:  Model层是API请求的原始数据,充当DTO(数据传输对象),当然,用字典也是可以的,编程么,要灵活一些.Model ...

  6. 淘宝JAVA中间件Diamond详解之简介&快速使用 管理持久配置的系统

    http://my.oschina.net/u/435621/blog/270483?p=1 淘宝JAVA中间件Diamond详解(一)---简介&快速使用 大家好,今天开始为大家带来我们通用 ...

  7. mysql5.7忘记密码时,修改root密码

    (1).由于MySQL5.7在安装完后,第一次启动时,会在root目录下生产一个随机的密码,文件名为 .mysql_secret 所以,登录时需要用随机密码登录,然后通过以下命令修改密码 “SET P ...

  8. Andoird通信之简单聊天ChatApp

    Android通信,大体上的逻辑是跟Java上的通信是差不多的,只是因为Android线程不能直接访问UI界面组件,所以在处理的时候有些麻烦,只要是通过Handle处理. 接下来是一个简单地手机聊天A ...

  9. 【MySQL】乐观锁和悲观锁

    最近学习了一下数据库的悲观锁和乐观锁,根据自己的理解和网上参考资料总结如下: 悲观锁介绍(百科): 悲观锁,正如其名,它指的是对数据被外界(包括本系统当前的其他事务,以及来自外部系统的事务处理)修改持 ...

  10. SQL Server 2008中SQL之WaitFor

    SQL Server 2008中SQL应用系列--目录索引 在SQL Server 2005以上版本中,在一个增强的WaitFor命令,其作用可以和一个job相当.但使用更加简捷. 看MSDN: ht ...