[雪峰磁针石博客]python库介绍-collections:高性能容器数据类型

本文涉及的产品
容器镜像服务 ACR,镜像仓库100个 不限时长
简介: 简介 2.4新增 源代码:Lib/collections.py and Lib/_abcoll.py 提供了替换dict, list, set和tuple的数据类型。 主要类型如下: namedtuple(): 命名元组,创建有名字域的元组子类的工厂函数。

简介

2.4新增

源代码:Lib/collections.py and Lib/_abcoll.py

提供了替换dict, list, set和tuple的数据类型。

主要类型如下:

  • namedtuple(): 命名元组,创建有名字域的元组子类的工厂函数。python 2.6新增。
  • deque:双端队列,类似于列表,两端进栈和出栈都比较快速。python 2.4新增。
  • Counter:字典的子类,用于统计哈希对象。python 2.7新增。
  • OrderedDict:有序字典,字典的子类,记录了添加顺序。python 2.7新增。
  • defaultdict:dict的子类,调用一个工厂函数支持不存在的值。python 2.5新增。

还提供了抽象基类,用来测试类是否提供了特殊接口,不管是哈希或者映射。

Counter

计数器(Counter)是一个容器,用来跟踪值出现了多少次。和其他语言中的bag或multiset类似。

计数器支持三种形式的初始化。构造函数可以调用序列,包含key和计数的字典,或使用关键字参数。


import collections

print(collections.Counter(['a', 'b', 'c', 'a', 'b', 'b']))
print(collections.Counter({'a': 2, 'b': 3, 'c': 1}))
print(collections.Counter(a=2, b=3, c=1))

执行结果:

$ python3 collections_counter_init.py 
Counter({'b': 3, 'a': 2, 'c': 1})
Counter({'b': 3, 'a': 2, 'c': 1})
Counter({'b': 3, 'a': 2, 'c': 1})

注意key的出现顺序是根据计数的从大到小。

可以创建空的计数器,再update:


import collections

c = collections.Counter()
print('Initial :{0}'.format(c))

c.update('abcdaab')
print('Sequence:{0}'.format(c))

c.update({'a': 1, 'd': 5})
print('Dict    :{0}'.format(c))

执行结果:

 python3.5 collections_counter_update.py*
Initial :Counter()
Sequence:Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1})
Dict    :Counter({'d': 6, 'a': 4, 'b': 2, 'c': 1})

访问计数


import collections

c = collections.Counter('abcdaab')

for letter in 'abcde':
    print('{0} : {1}'.format(letter, c[letter]))

执行结果:


$ python3.5 collections_counter_get_values.py 
a : 3
b : 2
c : 1
d : 1
e : 0

注意这里不存在的元素也会统计为0。

elements方法可以列出所有元素:


import collections

c = collections.Counter('extremely')
c['z'] = 0
print(c)
print(list(c.elements()))

执行结果:


$ python3.5 collections_counter_elements.py 
Counter({'e': 3, 'y': 1, 'r': 1, 'x': 1, 'm': 1, 'l': 1, 't': 1, 'z': 0})
['y', 'r', 'x', 'm', 'l', 't', 'e', 'e', 'e']

注意后面并没有输出计数为0的元素。

most_common()可以提取出最常用的元素。


import collections

c = collections.Counter()
with open('/etc/adduser.conf', 'rt') as f:
    for line in f:
        c.update(line.rstrip().lower())

print('Most common:')
for letter, count in c.most_common(3):
    print('{0}: {1}'.format(letter, count))

执行结果:


$ python3.5 collections_counter_most_common.py 
Most common:
 : 401
e: 310
s: 221

Counter还支持算术和集合运算,它们都只会保留数值为正整数的key。


import collections
import pprint

c1 = collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])
c2 = collections.Counter('alphabet')

print('C1:')
pprint.pprint(c1)
print('C2:')
pprint.pprint(c2)

print('\nCombined counts:')
print(c1 + c2)

print('\nSubtraction:')
print(c1 - c2)

print('\nIntersection (taking positive minimums):')
print(c1 & c2)

print('\nUnion (taking maximums):')
print(c1 | c2)

执行结果:


$ python3 collections_counter_arithmetic.py
C1:
Counter({'b': 3, 'a': 2, 'c': 1})
C2:
Counter({'a': 2, 't': 1, 'l': 1, 'e': 1, 'b': 1, 'p': 1, 'h': 1})

Combined counts:
Counter({'b': 4, 'a': 4, 'p': 1, 'e': 1, 'c': 1, 't': 1, 'l': 1, 'h': 1})

Subtraction:
Counter({'b': 2, 'c': 1})

Intersection (taking positive minimums):
Counter({'a': 2, 'b': 1})

Union (taking maximums):
Counter({'b': 3, 'a': 2, 'p': 1, 'e': 1, 'c': 1, 't': 1, 'l': 1, 'h': 1})

上面的例子让人觉得collections只能处理单个字符。其实不是这样的,请看标准库中的实例。


from collections import Counter
import pprint
import re

cnt = Counter()

for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
    cnt[word] += 1
pprint.pprint(cnt)
cnt = Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
pprint.pprint(cnt)

words = re.findall('\w+', open('/etc/adduser.conf').read().lower())
print(Counter(words).most_common(10))

执行结果:


$ python3 collections_counter_normal.py
Counter({'blue': 3, 'red': 2, 'green': 1})
Counter({'blue': 3, 'red': 2, 'green': 1})
[('the', 27), ('is', 13), ('be', 12), ('if', 12), ('will', 12), ('user', 10), ('home', 9), ('default', 9), ('to', 9), ('users', 8)]

第1段代码和第2段的代码效果式样的,后面一段代码通过Counter实现了简单的单词的统计功能。比如面试题:使用python打印出/etc/ssh/sshd_config出现次数最高的10个单词及其出现次数。

下面看看Counter的相关定义:

class collections.Counter([iterable-or-mapping]) 。注意Counter是无序的字典。在key不存在的时候返回0. c['sausage'] = 0。设置值为0不会删除元素,要使用del c['sausage']。

除了标准的字典方法,额外增加了:

elements() :返回一个包含所有元素的迭代器,忽略小于1的计数。

most_common([n]):返回最常用的元素及其计数的列表。默认返回所有元素。

subtract([iterable-or-mapping]) :相减。

namedtuple

命名元组和普通元组的的内存效率差不多。它不会针对每个实例生成字典。


import collections

Person = collections.namedtuple('Person', 'name age gender')

print('Type of Person:{0}'.format(type(Person)))

bob = Person(name='Bob', age=30, gender='male')
print('\nRepresentation: {0}'.format(bob))

jane = Person(name='Jane', age=29, gender='female')
print('\nField by name: {0}'.format(jane.name))

print('\nFields by index:')
for p in [bob, jane]:
    print('{0} is a {1} year old {2}'.format(*p))


执行结果:


$ python3 collections_namedtuple_person.py
Type of Person:<class 'type'>

Representation: Person(name='Bob', age=30, gender='male')

Field by name: Jane

Fields by index:
Bob is a 30 year old male
Jane is a 29 year old female

从上例可以看出命名元组Person类和excel的表头类似,给下面的每个列取个名字,真正excel行数据则存储在Person类的实例中。好处在于可以jane.name这样的形式访问,比记元组的index要直观。

注意列名在实现内部其实是个标识符,所以不能和关键字冲突,只能用字母或者下划线开头。下例会报错:


import collections

try:
    collections.namedtuple('Person', 'name class age gender')
except ValueError as err:
    print(err)

try:
    collections.namedtuple('Person', 'name age gender age')
except ValueError as err:
    print(err)

执行结果:


$ python3 collections_namedtuple_bad_fields.py 
Type names and field names cannot be a keyword: 'class'
Encountered duplicate field name: 'age'

设置rename=True,列名会在冲突时自动重命名,不过这种重命名并不美观。


import collections

with_class = collections.namedtuple('Person', 'name class age gender',
                                    rename=True)
print(with_class._fields)

two_ages = collections.namedtuple('Person', 'name age gender age',
                                  rename=True)
print(two_ages._fields)

执行结果:


$ python collections_namedtuple_rename.py
('name', '_1', 'age', 'gender')
('name', 'age', 'gender', '_3')
  • 定义

collections.namedtuple(typename, field_names, verbose=False) 返回一个命名元组类。如果verbose为True,会打印类定义信息

命名元组在处理数据库的时候比较有用:

ChainMap 映射链

用于查找多个字典。

ChainMap管理一系列字典,按顺序根据key查找值。

  • 访问值:

API和字典类似。

collections_chainmap_read.py


import collections

a = {'a': 'A', 'c': 'C'}
b = {'b': 'B', 'c': 'D'}

m = collections.ChainMap(a, b)

print('Individual Values')
print('a = {}'.format(m['a']))
print('b = {}'.format(m['b']))
print('c = {}'.format(m['c']))
print()

print('m = {}'.format(m))
print('Keys = {}'.format(list(m.keys())))
print('Values = {}'.format(list(m.values())))
print()

print('Items:')
for k, v in m.items():
    print('{} = {}'.format(k, v))
print()

print('"d" in m: {}'.format(('d' in m)))

执行结果:


$ python3 collections_chainmap_read.py 
Individual Values
a = A
b = B
c = C

m = ChainMap({'c': 'C', 'a': 'A'}, {'c': 'D', 'b': 'B'})
Keys = ['c', 'a', 'b']
Values = ['C', 'A', 'B']

Items:
c = C
a = A
b = B

"d" in m: False
  • 调整顺序

collections_chainmap_reorder.py


import collections

a = {'a': 'A', 'c': 'C'}
b = {'b': 'B', 'c': 'D'}

m = collections.ChainMap(a, b)

print(m.maps)
print('c = {}\n'.format(m['c']))

# reverse the list
m.maps = list(reversed(m.maps))

print(m.maps)
print('c = {}'.format(m['c']))

执行结果:


$ python3 collections_chainmap_reorder.py
[{'c': 'C', 'a': 'A'}, {'c': 'D', 'b': 'B'}]
c = C

[{'c': 'D', 'b': 'B'}, {'c': 'C', 'a': 'A'}]
c = D
  • 更新值

更新原字典:

collections_chainmap_update_behind.py


import collections

a = {'a': 'A', 'c': 'C'}
b = {'b': 'B', 'c': 'D'}

m = collections.ChainMap(a, b)
print('Before: {}'.format(m['c']))
a['c'] = 'E'
print('After : {}'.format(m['c']))

执行结果


$ python3 collections_chainmap_update_behind.py

Before: C
After : E

直接更新ChainMap:

collections_chainmap_update_directly.py


import collections

a = {'a': 'A', 'c': 'C'}
b = {'b': 'B', 'c': 'D'}

m = collections.ChainMap(a, b)
print('Before:', m)
m['c'] = 'E'
print('After :', m)
print('a:', a)

执行结果


$ python3 collections_chainmap_update_directly.py

Before: ChainMap({'c': 'C', 'a': 'A'}, {'c': 'D', 'b': 'B'})
After : ChainMap({'c': 'E', 'a': 'A'}, {'c': 'D', 'b': 'B'})
a: {'c': 'E', 'a': 'A'}

ChainMap可以方便地在前面插入字典,这样可以避免修改原来的字典。

collections_chainmap_new_child.py


import collections

a = {'a': 'A', 'c': 'C'}
b = {'b': 'B', 'c': 'D'}

m1 = collections.ChainMap(a, b)
m2 = m1.new_child()

print('m1 before:', m1)
print('m2 before:', m2)

m2['c'] = 'E'

print('m1 after:', m1)
print('m2 after:', m2)

执行结果


$ python3 collections_chainmap_new_child.py
m1 before: ChainMap({'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'})
m2 before: ChainMap({}, {'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'})
m1 after: ChainMap({'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'})
m2 after: ChainMap({'c': 'E'}, {'a': 'A', 'c': 'C'}, {'b': 'B', 'c': 'D'})

还可以通过传入字典的方式

collections_chainmap_new_child_explicit.py


import collections

a = {'a': 'A', 'c': 'C'}
b = {'b': 'B', 'c': 'D'}
c = {'c': 'E'}

m1 = collections.ChainMap(a, b)
m2 = m1.new_child(c)

print('m1["c"] = {}'.format(m1['c']))
print('m2["c"] = {}'.format(m2['c']))

执行结果


$ python3 collections_chainmap_new_child_explicit.py
m1["c"] = C
m2["c"] = E

另外一种等价的方式:


m2 = collections.ChainMap(c, *m1.maps)

参考资料

相关文章
|
3天前
|
数据处理 Python
如何使用Python的Pandas库进行数据排序和排名
【4月更文挑战第22天】Pandas Python库提供数据排序和排名功能。使用`sort_values()`按列进行升序或降序排序,如`df.sort_values(by=&#39;A&#39;, ascending=False)`。`rank()`函数用于计算排名,如`df[&#39;A&#39;].rank(ascending=False)`。多列操作可传入列名列表,如`df.sort_values(by=[&#39;A&#39;, &#39;B&#39;], ascending=[True, False])`和分别对&#39;A&#39;、&#39;B&#39;列排名。
13 2
|
2天前
|
机器学习/深度学习 算法 数据挖掘
PYTHON银行机器学习:回归、随机森林、KNN近邻、决策树、高斯朴素贝叶斯、支持向量机SVM分析营销活动数据|数据分享-2
PYTHON银行机器学习:回归、随机森林、KNN近邻、决策树、高斯朴素贝叶斯、支持向量机SVM分析营销活动数据|数据分享
24 1
|
1天前
|
机器学习/深度学习 算法 Python
数据分享|Python决策树、随机森林、朴素贝叶斯、KNN(K-最近邻居)分类分析银行拉新活动挖掘潜在贷款客户
数据分享|Python决策树、随机森林、朴素贝叶斯、KNN(K-最近邻居)分类分析银行拉新活动挖掘潜在贷款客户
19 4
|
1天前
|
机器学习/深度学习 算法 算法框架/工具
数据分享|PYTHON用KERAS的LSTM神经网络进行时间序列预测天然气价格例子
数据分享|PYTHON用KERAS的LSTM神经网络进行时间序列预测天然气价格例子
19 0
|
1天前
|
机器学习/深度学习 数据挖掘 网络架构
Python对商店数据进行lstm和xgboost销售量时间序列建模预测分析
Python对商店数据进行lstm和xgboost销售量时间序列建模预测分析
12 0
|
2天前
|
数据挖掘 数据处理 索引
如何使用Python的Pandas库进行数据筛选和过滤?
Pandas是Python数据分析的核心库,提供DataFrame数据结构。基本步骤包括导入库、创建DataFrame及进行数据筛选。示例代码展示了如何通过布尔索引、`query()`和`loc[]`方法筛选`Age`大于19的记录。
10 0
|
4天前
|
Python
如何使用Python的Pandas库进行数据缺失值处理?
Pandas在Python中提供多种处理缺失值的方法:1) 使用`isnull()`检查;2) `dropna()`删除含缺失值的行或列;3) `fillna()`用常数、前后值填充;4) `interpolate()`进行插值填充。根据需求选择合适的方法处理数据缺失。
35 9
|
6天前
|
索引 Python
如何使用Python的Pandas库进行数据透视表(pivot table)操作?
使用Pandas在Python中创建数据透视表的步骤包括:安装Pandas库,导入它,创建或读取数据(如DataFrame),使用`pd.pivot_table()`指定数据框、行索引、列索引和值,计算聚合函数(如平均分),并可打印或保存结果到文件。这允许对数据进行高效汇总和分析。
10 2
|
6天前
|
JSON 关系型数据库 数据库
《Python 简易速速上手小册》第6章:Python 文件和数据持久化(2024 最新版)
《Python 简易速速上手小册》第6章:Python 文件和数据持久化(2024 最新版)
33 0
|
7天前
|
机器学习/深度学习 Python 数据处理
Python中利用长短期记忆模型LSTM进行时间序列预测分析 - 预测电力负荷数据
Python中利用长短期记忆模型LSTM进行时间序列预测分析 - 预测电力负荷数据
31 0
Python中利用长短期记忆模型LSTM进行时间序列预测分析 - 预测电力负荷数据