collections模块

collections模块在内置数据类型(dict、list、set、tuple)的基础上,还提供了几个额外的数据类型:ChainMap、Counter、deque、defaultdict、namedtuple和OrderedDict等。

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

namedtuple

namedtuple是一个函数,它用来创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。

这样一来,我们用namedtuple可以很方便地定义一种数据类型,它具备tuple的不变性,又可以根据属性来引用,使用十分方便。

>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>>
>>> p = Point(1,2)
>>> p.x
1
>>> p.y
2
>>> Circle = namedtuple('Circle', ['x', 'y', 'r'])
>>> c = Circle(1,2,3)
>>> c
Circle(x=1, y=2, r=3)
>>> c.x
1
>>> c.y
2
#namedtuple('名称', [属性list]):

可以验证创建的Point对象是tuple的一种子类:

>>> Point = namedtuple('Point',['x1','y1','x2','y2'])
>>> p = Point('1','2','3','4')
>>> p
Point(x1='1', y1='2', x2='3', y2='4')
>>> p.x1
'1'
>>> isinstance(p,Point)
True
>>> isinstance(p,tuple)
True

deque

使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢了,因为list是线性存储,数据量大的时候,插入和删除效率很低。

deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈:

>>> from collections import deque
>>> q = deque(['a', 'b', 'c'])
>>> q.appendleft
<built-in method appendleft of collections.deque object at 0x028F8228>
>>> q.appendleft('')
>>> q
deque(['', 'a', 'b', 'c'])
>>> q.append('')
>>> q
deque(['', 'a', 'b', 'c', ''])
>>> q.popleft()
''
>>> q
deque(['a', 'b', 'c', ''])
>>> q.pop()
''
>>> q
deque(['a', 'b', 'c'])

deque除了实现list的append()pop()外,还支持appendleft()popleft(),这样就可以非常高效地往头部添加或删除元素。

defaultdict

使用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值,就可以用defaultdict

deque(['a', 'b', 'c'])
>>> from collections import defaultdict
>>> d = defaultdict(lambda:'N/A')
>>> d
defaultdict(<function <lambda> at 0x02A1F970>, {})
>>> d['key1']=1
>>> d['key1']
1
>>> d['key2']
'N/A'
>>> from collections import defaultdict
>>> d = defaultdict(0) Traceback (most recent call last):
File "<pyshell#173>", line 1, in <module>
d = defaultdict(0)
TypeError: first argument must be callable or None
>>> d = defaultdict(str)
>>> d
defaultdict(<type 'str'>, {})
>>> d['x']
''
>>> d = defaultdict(int)
>>> d['x']
0

注意默认值是调用函数返回的而函数在创建defaultdict对象时传入

除了在Key不存在时返回默认值,defaultdict的其他行为跟dict是完全一样的。

OrderedDict

使用dict时,Key是无序的。在对dict做迭代时,我们无法确定Key的顺序。

如果要保持Key的顺序,可以用OrderedDict

>>> from collections import OrderedDict
>>> d = dict([('a',1),('b',2),('c',3)])
>>> d
{'a': 1, 'c': 3, 'b': 2}
>>> od = OrderedDict([('a',1),('b',2),('c',3)])
>>> od
OrderedDict([('a', 1), ('b', 2), ('c', 3)])

注意,OrderedDict的Key会按照插入的顺序排列,不是Key本身排序:

>>> od = OrderedDict()
>>> od['z'] = 1
>>> od['y'] = 2
>>> od['x'] = 3
>>> od.keys() # 按照插入的Key的顺序返回
['z', 'y', 'x']

OrderedDict可以实现一个FIFO(先进先出)的dict,当容量超出限制时,先删除最早添加的Key:

from collections import OrderedDict

class LastUpdatedOrderedDict(OrderedDict):

    def __init__(self, capacity):
super(LastUpdatedOrderedDict, self).__init__()
self._capacity = capacity def __setitem__(self, key, value):
containsKey = 1 if key in self else 0
if len(self) - containsKey >= self._capacity:
last = self.popitem(last=False)
print 'remove:', last
if containsKey:
del self[key]
print 'set:', (key, value)
else:
print 'add:', (key, value)
OrderedDict.__setitem__(self, key, value)

Counter

Counter是一个简单的计数器,例如,统计字符出现的个数:

>>> from collections import Counter
>>> c = Counter()
>>> for ch in 'programming':
... c[ch] = c[ch] + 1
...
>>> c
Counter({'g': 2, 'm': 2, 'r': 2, 'a': 1, 'i': 1, 'o': 1, 'n': 1, 'p': 1})

Counter实际上也是dict的一个子类,上面的结果可以看出,字符'g''m''r'各出现了两次,其他字符各出现了一次。

案例:

统计一篇英文文章内每个单词出现频率,并返回出现频率最高的前3个单词及其出现次数

txt_content = '''She had been shopping with her Mom in Wal-Mart.
She must have been 6 years old, this beautiful brown haired, freckle-faced image of innocence.
It was pouring outside. The kind of rain that gushes over the top of rain gutters,
so much in a hurry to hit the Earth, it has no time to flow down the spout.
We all stood there under the awning and just inside the door of the Wal-Mart.
We all waited, some patiently, others irritated,
because nature messed up their hurried day.
I am always mesmerized by rainfall.
I get lost in the sound and sight of the heavens washing away the dirt and dust of the world.
Memories of running, splashing so carefree as a child come pouring in as a welcome reprieve from the worries of my day.
'''

使用传统字典

def str_count(s):
"""
统计英文单词出现次数
:param s:
:return:
"""
d = dict()
s = re.split('\W+', s.strip()) # 去掉回车,逗号等非英文和数字字符
for x in s:
if x not in d:
d[x] = 1
else:
d[x]+=1
return d if __name__ == '__main__':
d1 = str_count(txt_content)
print(sorted(d1.items(), key = lambda d:d[1],reverse=True)[:3])

使用defaultdict

from collections import defaultdict
from collections import Counter
import re def str_count(s):
"""
统计英文单词出现次数
:param s:
:return:
"""
d = defaultdict(int)
s = re.split('\W+', s.strip()) # 去掉回车,逗号等非英文和数字字符
for x in s:
d[x] += 1
return d if __name__ == '__main__':
d1 = str_count(txt_content)
print(sorted(d1.items(), key=lambda d: d[1], reverse=True)[:3])

使用counter

from collections import Counter
import re def str_count(s):
"""
统计英文单词出现次数
:param s:
:return:
"""
c = Counter()
s = re.split('\W+', s.strip()) # 去掉回车,逗号等非英文和数字字符
c.update(s)
return c if __name__ == '__main__':
c = str_count(txt_content)
print(c.most_common(3))

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模块

    collections模块基本介绍 collections在通用的容器dict,list,set和tuple之上提供了几个可选的数据类型 namedtuple() factory function f ...

  4. Python collections 模块用法举例

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

  5. Python——collections模块、time模块、random模块、os模块、sys模块

    1. collections模块 (1)namedtuple # (1)点的坐标 from collections import namedtuple Point = namedtuple('poin ...

  6. python collections模块详解

    参考老顽童博客,他写的很详细,例子也很容易操作和理解. 1.模块简介 collections包含了一些特殊的容器,针对Python内置的容器,例如list.dict.set和tuple,提供了另一种选 ...

  7. python collections模块 之 defaultdict

    defaultdict 是 dict 的子类,因此 defaultdict 也可被当成 dict 来使用,dict 支持的功能,defaultdict 基本都支持.但它与 dict 最大的区别在于,如 ...

  8. python collections 模块 之 deque

    class collections.deque(iterable[,maxlen]): 返回 由可迭代对象初始化的 从左向右的 deque 对象. maxlen: deque 的最大长度,一旦长度超出 ...

  9. python collections 模块 之namedtuple

    namedtuple collections.namedtuple(typename, filed_name, *, rename=False, module=None) 创建一个以 typename ...

随机推荐

  1. TPL DataFlow初探(二)

    上一篇简单的介绍了TDF提供的一些Block,通过对这些Block配置和组合,可以满足很多的数据处理的场景.这一篇将继续介绍与这些Block配置的相关类,和挖掘一些高级功能. 在一些Block的构造函 ...

  2. spring 自定义标签的实现

    在我们进行Spring 框架开发中,估计用到最多的就是bean 标签吧,其实在Spring中像<mvc/><context/>这类标签以及在dubbo配置的标签都是属于自定义的 ...

  3. Yii2增删改查

    Controller <?php namespace frontend\controllers; use frontend\models\User; use yii\data\Paginatio ...

  4. paired-end reads的拼接

    paired-end reads的拼接 发表于2012 年 8 月 13 日 Velvet中paired-end reads的拼接 文件格式 要将两头测序(paired-end)的reads放到同一个 ...

  5. 搭建RESTful API来使用Fabric Node SDK 开篇

    在Balance-Transfer中,有关于Node SDK比较完备的例子. SDK的官方文档在这里:https://fabric-sdk-node.github.io/ Balance-Transf ...

  6. 【Git】 GitLab简单使用

    本例介绍简单实用GitLab,安装请参照[Git] GitLab服务器社区版安装与配置 1.用户和组的管理 a.创建组,在首页点击Create a group b.创建用户,在首页点击Add peop ...

  7. [c#.net]未能加载文件或程序集“”或它的某一个依赖项。系统找不到指定的文件

    问题是这样嘀: 项目采用了三层架构和工厂模式,并借鉴了PetShop的架构,因为这个项目也是采用分布式的数据库,目前只有三个数据库,主要出于提高访问性能考虑. 原来是按照网上对PetShop的介绍来给 ...

  8. python 实践项目

    项目一:让用户输入圆的半径,告诉用户圆的面积 思路: 1.首先需要让用户输入一个字符串,即圆的半径 2.判断用户输入的字符串是否为数字  isalpha 3.求圆的面积需要调用到math模块,所以要导 ...

  9. Python11/26--mysql之视图/触发器/事务/存储过程

    视图: 1.什么是视图 视图就是通过查询得到一张虚拟表,然后保存下来,下次用的时候直接使用即可 2.为什么用视图 如果要频繁使用一张虚拟表,可以不用重复查询 3.如何用视图 select * from ...

  10. Python开发——3.基本数据类型之列表、元组和字典

    一.列表(list) 1.列表的格式 li = [11,22,"kobe",["lakers","ball",11],(11,22,),{& ...