python中SortedList类的用法详解
SortedList类是python第三方库sortedcontainers中的提供的一种高效的方式来存储有序的元素集合,同时支持快速的插入、删除和查找操作。
SortedList类的特点:
1.排序列表的值始终保持有序。
2.排序列表中的值必须可以比较。
3.值的总顺序在存储于排序列表期间不得改变。
4.插入、删除和查找操作的时间复杂度通常是对数级别的,这比标准列表的线性时间复杂度要好得多,特别是在处理大量数据时。
5.特别适用于需要频繁进行插入、删除和查找操作,同时需要保持元素排序的场景,如优先级队列、数据排序、范围查询等。
使用SortedList类,首先需要安装第三方库sortedcontainers:
pip install sortedcontainers
在使用的时候,从sortedcontainers导入SortedList类:
from sortedcontainers import SortedList
SortedList类提供的添加值的方法:add、update
s = SortedList()
s.add(1)
s.add(2)
print("add元素后:{}".format(s))
s = SortedList()
s.update([1,2,3,4,5,6])
print("update元素后:{}".format(s))
SortedList类提供的移除值的方法:clear、discard、remove、pop
s1 = [2,6,4,5,7,8,9,0]
s2 = SortedList(s1)
print(s2)
s2.clear()
print("clear元素后:{}".format(s2))
s1 = [2,6,4,5,7,8,9,0]
s2.update(s1)
print(s2)
s2.discard(2)
print("discard元素2后:{}".format(s2))
s2.discard(11)
print("discard元素11后:{}".format(s2))
s1 = [2,6,4,5,7,8,9,0]
s2.update(s1)
print(s2)
s2.remove(4)
print("remove元素4后:{}".format(s2))
s2.remove(1)
print("remove元素1后:{}".format(s2))
s2.clear()
s1 = [2,6,4,5,7,8,9,0]
s2.update(s1)
print(s2)
res = s2.pop()
print(res)
print("pop索引为-1的元素后:{}".format(s2))
res1 = s2.pop(2)
print(res1)
print("pop索引为1的元素后:{}".format(s2))
SortedList类提供的查找值的方法:bisect_left、bisect_right、count、index
s3 = SortedList([1,3,2,4,6])
print("s3为:{}".format(s3))
v = s3.bisect_left(7)
print("bisect_left插入值为7的元素后:{}".format(v))
v1 = s3.bisect_left(2)
print("bisect_left插入值为2的元素后:{}".format(v1))
s4 = SortedList([1,3,2,4,6])
print("s4为:{}".format(s4))
v3 = s4.bisect_right(3)
print("bisect_right插入值为3的元素后:{}".format(v3))
v4 = s4.bisect_right(8)
print("bisect_right插入值为8的元素后:{}".format(v4))
s5 = SortedList([1,1,2,3,4])
print("s5:{}".format(s5))
v5 = s5.count(1)
print("元素1的count次数为:{}".format(v5))
v6 = s5.count(7)
print("元素7的count次数为:{}".format(v6))
s6 = SortedList([1,1,2,3,4])
v7 = s6.index(1)
print("元素1的index为:{}".format(v7))
v8 = s6.index(1,start=1, stop=2)
print("元素1的index为:{}".format(v8))
SortedList类提供了一些迭代值的方法:irange、islice
minimum
到 maximum
的值迭代器。默认情况下,minimum
和 maximum
都设置为 None
,这自动包括了排序列表的开始和结束。参数 inclusive
是一个布尔值对,表示是否应将最小值和最大值包含在范围内。默认值为(True,True),使得范围包括最小值和最大值。当 reverse
为 True
时迭代器中的值将以相反顺序生成;reverse
默认为 False
。s7 = SortedList([1,2,3,4,5])
print("s7:{}".format(s7))
l = s7.irange(2,4, (True, True), False)
for i in l:
print("i的值:{}".format(i))
l1 = s7.irange(1,3, (False, True), True)
for i1 in l1:
print("i1的值:{}".format(i1))
start
到stop
对排序列表进行切片。start
和 stop
索引分别被视为包含和排除。默认情况下 start
和 stop
都为 None
,这会自动包含排序列表的开始和结束。reverse
默认为 False
,当 reverse
为 True
时迭代器中的值将以反序生成。s8 = SortedList([1,2,3,4,5,6])
it = s8.islice(1,3, True)
for i in it:
print("i的值{}".format(i))
it1 = s8.islice(1, 3, False)
for j in it1:
print("j的值{}".format(j))
SortedList类提供的copy方法
s9 = SortedList([1,2,3,4,3,2])
print("s9:{}".format(s9))
s10 = s9.copy()
print("s10:{}".format(s10))
作者:进击的小陈