SortedList

SortedListsortedcontainers 库中的一个数据结构,它提供了一个有序列表,能够自动对存储的元素进行排序,并且支持高效的插入、删除和查找操作。下面从多个方面详细解释 SortedList

安装

在使用 SortedList 之前,需要先安装 sortedcontainers 库,可以使用以下命令进行安装:

bash 复制代码
pip install sortedcontainers

基本使用示例

python 复制代码
from sortedcontainers import SortedList

# 创建一个空的 SortedList
sorted_list = SortedList()

# 向 SortedList 中添加元素
sorted_list.add(3)
sorted_list.add(1)
sorted_list.add(2)

print(sorted_list)  # 输出: SortedList([1, 2, 3])

从上述示例可以看出,即使元素是无序添加的,SortedList 会自动将它们排序。

主要特性

1. 自动排序

每次向 SortedList 中添加或删除元素时,它都会自动维护元素的有序性。无论何时访问列表中的元素,它们始终是按升序排列的。

python 复制代码
from sortedcontainers import SortedList

sl = SortedList([5, 2, 8])
print(sl)  # 输出: SortedList([2, 5, 8])

sl.add(3)
print(sl)  # 输出: SortedList([2, 3, 5, 8])
2. 高效的插入和删除操作

SortedList 内部使用了一种平衡树(通常是 B 树)来存储元素,这使得插入和删除操作的时间复杂度为 O(logn)O(log n)O(logn),其中 nnn 是列表中元素的数量。

python 复制代码
from sortedcontainers import SortedList

sl = SortedList([1, 2, 3, 4, 5])
sl.remove(3)
print(sl)  # 输出: SortedList([1, 2, 4, 5])
3. 支持索引访问

可以像普通列表一样通过索引来访问 SortedList 中的元素,索引从 0 开始。

python 复制代码
from sortedcontainers import SortedList

sl = SortedList([10, 20, 30, 40, 50])
print(sl[2])  # 输出: 30
4. 支持切片操作

SortedList 也支持切片操作,返回一个新的 SortedList 对象。

python 复制代码
from sortedcontainers import SortedList

sl = SortedList([1, 2, 3, 4, 5])
sliced = sl[1:3]
print(sliced)  # 输出: SortedList([2, 3])
5. 支持查找操作

可以使用 bisect_leftbisect_right 方法来查找元素的插入位置,时间复杂度为 O(logn)O(log n)O(logn)。

python 复制代码
from sortedcontainers import SortedList

sl = SortedList([1, 3, 5, 7, 9])
index = sl.bisect_left(4)
print(index)  # 输出: 2

常用方法

1. add(value)

SortedList 中添加一个元素,并自动对列表进行排序。

2. remove(value)

SortedList 中移除指定的元素,如果元素不存在会抛出 ValueError 异常。

3. pop(index=-1)

移除并返回指定索引位置的元素,默认移除最后一个元素。

4. clear()

清空 SortedList 中的所有元素。

5. bisect_left(value)bisect_right(value)

分别返回元素 valueSortedList 中应该插入的最左和最右位置。

应用场景

  • 需要频繁插入、删除元素并保持有序性的场景 :例如,在实现优先队列、事件调度器等场景中,SortedList 可以高效地维护元素的顺序。
  • 查找元素的插入位置 :可以利用 bisect_leftbisect_right 方法快速找到元素应该插入的位置,而无需手动遍历列表。

总之,SortedList 是一个功能强大且高效的数据结构,适用于需要自动排序和高效操作的场景。

相关推荐
洵有兮4 分钟前
python第四次作业
开发语言·python
kkoral5 分钟前
单机docker部署的redis sentinel,使用python调用redis,报错
redis·python·docker·sentinel
BoBoZz1919 分钟前
IterativeClosestPoints icp配准矩阵
python·vtk·图形渲染·图形处理
test管家41 分钟前
PyTorch动态图编程与自定义网络层实战教程
python
laocooon5238578861 小时前
python 收发信的功能。
开发语言·python
清水白石0081 小时前
《Python 责任链模式实战指南:从设计思想到工程落地》
开发语言·python·责任链模式
沛沛老爹1 小时前
Web开发者快速上手AI Agent:基于LangChain的提示词应用优化实战
人工智能·python·langchain·提示词·rag·web转型
宁大小白1 小时前
pythonstudy Day39
python·机器学习
拾贰_C1 小时前
【VSCode | python | anaconda | cmd | PowerShell】在没有进入conda环境时使用conda命令默认安装位置
vscode·python·conda
大千AI助手1 小时前
基于OpenAPI生成的 SDK 的工业级和消费级概念区别
人工智能·python·机器学习·openai·代码生成·openapi·大千ai助手