SortedDict
在插入、删除键值对后仍然可以按照键值自动维护顺序的字典。
from sortedcontainers import SortedDict
sd = SortedDict()
插入键值对
- 插入/更新单个键值对:
SortedDict.__setitem__(key, val),SortedDict[key]=val - 插入(如果键值不存在)的键值对:
SortedDict.setdefault(key, val) - 插入/更新多个键值对:
SortedDict.update({key1: val1, key2: val2, ...})
移除键值对
- 根据键值移除:
SortedDict.__delitem__(key),del SortedDict[key],SortedDict.pop(key) - 根据键值的索引移除:
SortedDict.popitem(index)
查询键值对
- 根据键值获取:
SortedDict[key],SortedDict.__getitem__(key) - 查询键值是否存在:
SortedDict.__contains__(key),key in SortedDict - 获取键值对(不存在,返回空):
SortedDict.get(key) - 根据键值索引获取:
SortedDict.peekitem(index) - 支持
SortedList包含的其他接口:SortedDict.bisect_left,SortedDict.bisect_right,SortedDict.index, …
Dict类内置接口支持
- 获取键的列表:
SortedDict.keys() - 获取值的列表:
SortedDict.values() - 获取键值对的列表:
SortedDict.items()
SortedSet
将可哈希的元素保持顺序的存放在列表里。
from sortedcollections import SortedSet
ss = SortedSet()
Set 类内置接口
- 查询元素接口:
SortedSet.__contains__(val) - 增加元素接口:
SortedSet.add(val),SortedSet.update(Iterable[val1, val2, ...]) - 移除元素接口:
SortedSet.discard(val),SortedSet.remove(val) - 集合操作接口:
SortedSet.difference(SortedSet),SortedSet.intersection(SortedSet),SortedSet.symmetric_difference(SortedSet),SortedSet.union(SortedSet)