器→工具, 术→技巧, 研发, 编程语言

Python模块:容器数据类型Collections

钱魏Way · · 398 次浏览

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

namedtuple() 生成可以使用名字来访问元素内容的tuple子类
deque 类似列表(list)的容器,实现了在两端快速添加(append)和弹出(pop)
Counter 字典的子类,提供了可哈希对象的计数功能
OrderedDict 字典的子类,保存了他们被添加的顺序
defaultdict 字典的子类,提供了一个工厂函数,为字典查询提供一个默认值
UserDict 封装了字典对象,简化了字典子类化
UserList 封装了列表对象,简化了列表子类化
UserString 封装了列表对象,简化了字符串子类化

namedtuple()

namedtuple主要用来产生可以使用名称来访问元素的数据对象,通常用来增强代码的可读性, 在访问一些tuple类型的数据时尤其好用。

# -*- coding: utf-8 -*-

from collections import namedtuple

websites = [
    ('百度', 'https://www.baidu.com/', '李彦宏'),
    ('阿里', 'https://www.taobao.com/', '马云'),
    ('腾讯', 'http://www.qq.com/', '马化腾')
]

Website = namedtuple('Website', ['name', 'url', 'founder'])

for website in websites:
    website = Website._make(website)
    print(website)

# 输出内容:
# Website(name='百度', url='https://www.baidu.com/', founder='李彦宏')
# Website(name='阿里', url='https://www.taobao.com/', founder='马云')
# Website(name='腾讯', url='http://www.qq.com/', founder='马化腾')

deque

deque其实是 double-ended queue 的缩写,翻译过来就是双端队列,它最大的好处就是实现了从队列 头部快速增加和取出对象: .popleft(), .appendleft() 。

你可能会说,原生的list也可以从头部添加和取出对象啊?就像这样:

l.insert(0, v)
l.pop(0)

但是值得注意的是,list对象的这两种用法的时间复杂度是 O(n) ,也就是说随着元素数量的增加耗时呈 线性上升。而使用deque对象则是 O(1) 的复杂度,所以当你的代码有这样的需求的时候, 一定要记得使用deque。作为一个双端队列,deque还提供了一些其他的好用方法,比如 rotate 等。

from collections import deque

q = deque(['a', 'b', 'c'])
q.append('x')
q.appendleft('y')
print(q)

# 输出内容:
# deque(['y', 'a', 'b', 'c', 'x'])

Counter

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

# -*- coding: utf-8 -*-
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.'''

c = Counter(s)
# 获取出现频率最高的5个字符
print(c.most_common(5))

# 输出内容:
# [(' ', 54), ('e', 32), ('s', 25), ('a', 24), ('t', 24)]

OrderedDict

有序词典就像常规词典一样,但有一些与排序操作相关的额外功能。由于内置的 dict 类获得了记住插入顺序的能力(在 Python 3.7 中保证了这种新行为),它变得不那么重要了。

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(<class 'list'>, {'male': ['John', 'Jack', 'Pony'], 'female': ['Lily', 'Lucy']})

参考链接:

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注