python模块 - collections模块

http://blog.csdn.net/pipisorry/article/details/46947833

集合库collection

collections模块介绍

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

1.namedtuple(): 生成可以使用名字来访问元素内容的tuple子类

2.deque: 双端队列,可以快速的从另外一侧追加和推出对象

3.Counter: 计数器,主要用来计数

4.OrderedDict: 有序字典

5.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.jbxue.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.jbxue.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:

# 一个无尽循环的跑马灯

------------->-------

http://blog.csdn.net/pipisorry/article/details/46947833

Counter计数器

It is kind of redundant, in that Collections already contains a class for doing this, called Counter. In this case, I need to first extract the second item from eachtuple, for which I can use a generator expression.

from collections import Counter

 

order_count =  Counter(menu_item for name, menu_item in order)

print order_count

 

# output

# Counter({

#    ‘Beer‘: 2,

#    ‘Steak‘: 2,

#    ‘Wine‘: 1,

#    ‘Veggie Burger‘: 1

# })

view rawcounter.py
hosted with ? by GitHub

Another, maybe better, example might be counting all the different lines that appear in a file. It becomes very simple.

with open(‘/some/file‘, ‘r‘) as f:

line_count = Counter(f)

计数器是一个非常常用的功能需求,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‘]})

[Python collections模块实例]

参考资料

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

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

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

from:http://blog.csdn.net/pipisorry/article/details/46947833

ref:

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-08-10 14:10:53

python模块 - collections模块的相关文章

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

1.collections模块 collections模块自Python 2.4版本开始被引入,包含了dict.set.list.tuple以外的一些特殊的容器类型,分别是: OrderedDict类:排序字典,是字典的子类.引入自2.7.namedtuple()函数:命名元组,是一个工厂函数.引入自2.6.Counter类:为hashable对象计数,是字典的子类.引入自2.7.deque:双向队列.引入自2.4.defaultdict:使用工厂函数创建字典,使不用考虑缺失的字典键.引入自2.

简介Python的collections模块中defaultdict类型

这里我们来简介Python的collections模块中defaultdict类型的用法,与内置的字典类最大的不同在于初始化上,一起来看一下: defaultdict 主要用来需要对 value 做初始化的情形.对于字典来说,key 必须是 hashable,immutable,unique 的数据,而 value 可以是任意的数据类型.如果 value 是 list,dict 等数据类型,在使用之前必须初始化为空,有些情况需要把 value 初始化为特殊值,比如 0 或者 ''. from c

Python中collections模块中的Counter()类

最近在刷leetcode,发现很多题目的思路都很相似.其中,collections模块中的Counter()多次在习题中碰到,很有必要对该知识点总结一下,加深理解. 1.collections模块 collections模块自Python 2.4 版本之后,引入除了dict.list.set.tuple以外的一些特俗容器,分别是: namedtuple():factory function for creating tuple subclasses with named fields(versi

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

namedtuple顾名思义,就是名字+元组的数据结构,下面就来看一下Python的collections模块中namedtuple结构使用示例 namedtuple 就是命名的 tuple,比较像 C 语言中 struct.一般情况下的 tuple 是 (item1, item2, item3,...),所有的 item 都只能按照 index 访问,没有明确的称呼,而 namedtuple 就是事先把这些 item 命名,以后可以方便访问. ? 1 2 3 4 5 6 7 8 9 10 11

python之collections模块(OrderDict,defaultdict)

前言: import collections print([name for name in dir(collections) if not name.startswith("_")]) ['AsyncIterable', 'AsyncIterator', 'Awaitable', 'ByteString', 'Callable', 'ChainMap', 'Container', 'Coroutine', 'Counter', 'Generator', 'Hashable', 'It

Python基础 collections模块

collections模块 collections模块在内置数据类型(dict.list.set.tuple)的基础上,还提供了几个额外的数据类型:ChainMap.Counter.deque.defaultdict.namedtuple和OrderedDict等. 1.namedtuple: 生成可以使用名字来访问元素内容的tuple子类2.deque: 双端队列,可以快速的从另外一侧追加和推出对象3.Counter: 计数器,主要用来计数4.OrderedDict: 有序字典5.defaul

python的Collections 模块

Collections 模块 知识点 Counter 类 defaultdict 类 namedtuple 类 在这个实验我们会学习 Collections 模块.这个模块实现了一些很好的数据结构,它们能帮助你解决各种实际问题. >>> import collections 这是如何导入这个模块,现在我们来看看其中的一些类. 1. Counter Counter 是一个有助于 hashable 对象计数的 dict 子类.它是一个无序的集合,其中 hashable 对象的元素存储为字典的

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

collections模块基本介绍 我们都知道,Python拥有一些内置的数据类型,比如str, int, list, tuple, dict等, collections模块在这些内置数据类型的基础上,提供了几个额外的数据类型: 1.namedtuple(): 生成可以使用名字来访问元素内容的tuple子类2.deque: 双端队列,可以快速的从另外一侧追加和推出对象3.Counter: 计数器,主要用来计数4.OrderedDict: 有序字典5.defaultdict: 带有默认值的字典 n

python time模块 sys模块 collections模块

一 collections模块 collections模块在内置的数据类型,比如:int.str.list.dict等基础之上额外提供了几种数据类型. 参考博客 http://www.pythoner.com/205.html 二 time模块 在Python中共有三种表达方式:1)timestamp 时间戳 2)tuple或者struct_time3)格式化字符串. 三者的转换关系示意图