Python-高阶数据结构:collections、bisect模块
Python以内置库的方式,提供除基本数据类型以外的扩展数据类型
Python collections模块用于扩展python的数据类型
Python bisect模块用于有序列表的插值
1 collections模块(内置库)
1.1 初始化字典 defaultdict
defaultdict
在字典dict的基础之上添加一个参数default_factory
(default_factory可以指定为list,set,int和其他任意的第三方和自定义class类型)
defaultdict(list)
在每个key第一次被使用时初始化value为[]
,可以使用list的方法defaultdict(set)
在每个key第一次被使用时初始化value为{}
,可以使用set的方法defaultdict(int)
在每个key第一次被使用时初始化value为0
,可以使用int的方法
1.1.1 defaultdict(int)
defaultdict(int)
可以对相同的key进行累加计数
from collections import defaultdict
sen='hello world'
d=defaultdict(int)
for key,value in sen:
d[key]+=1
print(d)
defaultdict(<class 'int'>, {'o': 2, 'h': 1, 'w': 1, 'l': 3, ' ': 1, 'd': 1, 'e': 1, 'r': 1})
1.1.2 defaultdict(list)
defaultdict(list)
可以建立一个key对多个value的映射
from collections import defaultdict
l=[('a',2),('b',3),('a',1),('b',4),('a',3),('a',1),('b',3)]
d=defaultdict(list)
for key,value in l:
d[key].append(value)
print(d)
>>defaultdict(<class 'list'>,{'a':[2,1,3,1],'b':[3,4,3]}
1.1.3 defaultdict(set)
defaultdict(set)
可以在defaultdict(list)的基础上去重
from collections import defaultdict
l=[('a',2),('b',3),('a',1),('b',4),('a',3),('a',1),('b',3)]
d=defaultdict(set)
for key,value in l:
d[key].update(value)
print(d)
>>defaultdict(<class 'set'>,{'a':{2,1,3},'b':{3,4}}
2 bisect模块(内置库)
bisect模块实现了 二分 (bisection) 算法 的模块,能够 保持序列 sequence 顺序不变 的情况下对其进行 二分查找和插入,适合用于降低对冗长序列查找的时间成本
左侧插入点:元素elem在序列sequence合适的插入点,如果序列中已存在,则放在相同元素的左侧
右侧插入点:元素elem在序列sequence合适的插入点,如果序列中已存在,则放在相同元素的右侧
bisect模块 | 说明 |
---|---|
bisect_left(sequence, elem) -> index | 返回elem在sequence中左侧插入点的index |
bisect_right(sequence, elem) -> index | 返回elem在sequence中右侧插入点的index |
bisect() | 同 bisect_right() |
insort_left(sequence, elem) -> index | 查找目标元素左侧插入点,并插入元素,直接修改原序列 |
insort_right(sequence, elem) -> index | 查找目标元素右侧插入点,并插入元素,直接修改原序列 |
insort() | 同insort_right() |
2.1 示例:按成绩评分
from bisect import *
def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
i = bisect(breakpoints, score)
return grades[i]
ret = [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]] # 列表解析式 按成绩划分等级
>>>['F', 'A', 'C', 'C', 'B', 'A', 'A']