from sortedcontainers import SortedDict
# 创建一个SortedDict对象
sd = SortedDict()
# 添加键值对
sd[3] = 'three'
sd[1] = 'one'
sd[2] = 'two'
# 打印SortedDict对象,会按照键的顺序排序
print(sd) # 输出: SortedDict({1: 'one', 2: 'two', 3: 'three'})
# 获取最小的键和最大的键
min_key = sd.peekitem(0)[0]
max_key = sd.peekitem(-1)[0]
print(f"最小的键是: {min_key}") # 输出: 最小的键是: 1
print(f"最大的键是: {max_key}") # 输出: 最大的键是: 3
# 删除一个键值对
del sd[2]
print(sd) # 输出: SortedDict({1: 'one', 3: 'three'})
from sortedcontainers import SortedDict 导入 SortedDict 类。sd = SortedDict() 创建一个空的 SortedDict 对象。SortedDict 会自动根据键进行排序。print(sd) 会按照键的顺序输出字典内容。peekitem(0) 获取最小键,peekitem(-1) 获取最大键。del 关键字删除指定键的键值对。希望这段代码和解释对你有帮助!
下一篇:python arima
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站