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. 网络请求Adapter添加数据

    一般在开发中我们都需要在listview中添加数据显示在界面上 1.首先我们会在布局中写一个listview <FrameLayout xmlns:android="http://sc ...

  2. Python基础-python简介(一)

    一.简介: python是一种面向对象的解释性计算机程序设计语言,由荷兰人Guido  von  Rossum于1989年的圣诞节发明. Python语言的特色: 1.python是一门解释性语言 解 ...

  3. tab页

    图片: 代码: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <t ...

  4. sqlserver 组内排序

    关键词 partition(分区函数[pɑː'tɪʃ(ə)n])  by 参考: https://www.cnblogs.com/sanlang/archive/2009/03/24/1420360. ...

  5. springboot 使用JPA自动生成Entity实体类的方法

    1. 2. 3.添加数据库 4. 5. 6. 7.点击OK完成. 8.去掉红色波浪线方法. 9.配置数据源 完成!

  6. 服务器重新启动,ftp重新连接问题

    服务器重新启动,发现FlashFXP无法连接了,估计是ftp没有启动, 1. 首先服务器要安装ftp软件,查看是否已经安装ftp软件下:   #which vsftpd   如果看到有vsftpd的目 ...

  7. 第一次spring会议

    1.今天查询了很多案例,找到了符合我们要求的案例,并进行了尝试. 2.昨天拍摄了宣传视频. 3.明天准备用C#限定格式输出TXT文件.

  8. js的事件委托机制

    如今的JavaScript技术界里最火热的一项技术应该是‘事件委托(event delegation)’了.使用事件委托技术能让你避免对特定的每个节点添加事件监听器:相反,事件监听器是被添加到它们的父 ...

  9. More x64 assembler fun-facts–new assembler directives(转载)

    原文地址 The Windows x64 ABI (Application Binary Interface) presents some new challenges for assembly pr ...

  10. 从服务器角度分析RPG游戏——NPC的AI

    最近主程有些忙,甩给我一些服务器的代码,零零散散总结了一些要素. java程序架构也是层层分析,先罗列出需要做的工作,然后从主干到细节依次实现.就这点而言,程序和绘画有很多类似的地方. 关于怪物AI类 ...