准备
pip3 install sortedcontainers
用法
SortedList
from sortedcontainers import SortedList
if __name__ == '__main__':
sorted_list = SortedList(key=lambda x: x * x)
sorted_list.add(-100)
sorted_list.add(1)
sorted_list.add(99)
print(list(sorted_list))
[1, 99, -100]
SortedDict
SortedDict只能对key排序,且所有的key必须是可比较的(理解错误请指正,感谢)
from sortedcontainers import SortedDict
if __name__ == '__main__':
sorted_dict = SortedDict()
sorted_dict[1] = 3
sorted_dict[2] = 2
print(sorted_dict)
SortedDict({1: 3, 2: 2})
===============================================
sorted_dict = SortedDict()
sorted_dict[1] = 3
sorted_dict["a"] = 2
print(sorted_dict)
TypeError: '<' not supported between instances of 'str' and 'int'
SortedSet
if __name__ == '__main__':
sorted_set = SortedSet(key=lambda x: x * x)
sorted_set.add(1)
sorted_set.add(-1)
sorted_set.add(1)
print(sorted_set)
SortedSet([1, -1], key=<function <lambda> at 0x000001D7E70A4598>)