
在使用`sortedcontainers`库中的`sortedset`时,直接修改集合中元素的排序键值会导致意外行为和错误。`sortedset`依赖于元素的键值(或其自身)在添加时保持稳定。正确的做法是先从`sortedset`中移除元素,修改其键值,然后再将其重新添加回集合,以确保内部结构和排序的完整性。
SortedSet是Python中一个高效的有序集合实现,它能够根据元素的自然顺序或通过自定义key函数指定的键值进行排序。其核心原理是维护一个内部数据结构(通常是跳表或红黑树),以便快速地查找、添加和删除元素,并始终保持元素的有序性。
当使用key参数初始化SortedSet时,例如SortedSet([items], key=lambda x: some_value_based_on_x),SortedSet会根据lambda函数返回的值来对元素进行排序。这意味着,如果元素的排序键值发生变化,SortedSet的内部结构必须能够感知到这个变化,并相应地调整元素的位置。
然而,SortedSet的实现并非设计为在元素仍在集合中时自动检测并响应其排序键值的变化。它的设计假设是,一旦元素被添加到集合中,其用于排序的键值在元素被移除之前是保持不变的。
考虑一个管理食物评分的系统,其中SortedSet用于存储特定菜系下的食物,并根据评分和食物名称进行排序。
from sortedcontainers import SortedSet
from typing import List
class FoodRatings:
def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):
self.food_map = {} # Food: [cuisine, rating, food]
self.cuisines_map = {} # Cuisine: SortedSet(Food)
for index in range(len(foods)):
self.food_map[foods[index]] = [cuisines[index], ratings[index], foods[index]]
if cuisines[index] not in self.cuisines_map:
# 初始化SortedSet,排序键为 (-rating, food_name)
self.cuisines_map[cuisines[index]] = SortedSet(
[], key=lambda x: (-self.food_map[x][1], self.food_map[x][2])
)
self.cuisines_map[cuisines[index]].add(foods[index])
def changeRating_incorrect(self, food: str, newRating: int) -> None:
cuisine = self.food_map[food][0]
# 错误做法:先修改评分(即修改了排序键),然后尝试移除和重新添加
self.food_map[food][1] = newRating # 此时food的排序键已改变
self.cuisines_map[cuisine].discard(food) # 尝试移除
self.cuisines_map[cuisine].add(food) # 重新添加在上述changeRating_incorrect函数中,当self.food_map[food][1] = newRating执行时,food元素在self.cuisines_map[cuisine]这个SortedSet中的排序键值就已经发生了变化。由于SortedSet的key函数lambda x: (-self.food_map[x][1], self.food_map[x][2])直接依赖于self.food_map[x][1],此时food在集合中的“旧键值”与“新键值”不一致。
当self.cuisines_map[cuisine].discard(food)被调用时,SortedSet会尝试根据food当前(已修改的)键值去查找并移除它。然而,food在集合内部的存储位置是基于其旧的键值计算的。因此,SortedSet可能无法找到该元素,或者找到错误的元素,从而导致KeyError(在某些情况下,如果内部实现尝试将元素视为列表,也可能出现'sushi' not in List这样的错误),或者更糟糕的是,导致集合内部数据结构损坏,产生不可预测的行为。
sortedcontainers库的文档明确指出了这一点:
Sorted set values must be hashable and comparable. The hash and total ordering of values must not change while they are stored in the sorted set.(有序集合的值必须是可哈希和可比较的。在值存储在有序集合中时,其哈希值和总排序不能改变。)
这意味着,任何影响元素哈希值或排序顺序的属性(尤其是被key函数引用的属性)都不应在元素仍在SortedSet中时被修改。
要正确地修改SortedSet中元素的排序键值,必须遵循“先移除,后修改,再添加”的原则。
class FoodRatings:
# ... (__init__ 方法同上) ...
def changeRating_correct(self, food: str, newRating: int) -> None:
cuisine = self.food_map[food][0]
# 正确做法:先从SortedSet中移除元素
self.cuisines_map[cuisine].discard(food)
# 然后修改元素的评分(即修改了排序键)
self.food_map[food][1] = newRating
# 最后将修改后的元素重新添加回SortedSet
self.cuisines_map[cuisine].add(food)
def highestRated(self, cuisine: str) -> str:
# 确保集合不为空
if not self.cuisines_map[cuisine]:
return "" # 或者抛出错误
return self.cuisines_map[cuisine][0]
# 示例代码重现
obj = FoodRatings(["kimchi","miso","sushi","moussaka","ramen","bulgogi"],
["korean","japanese","japanese","greek","japanese","korean"],
[9,12,8,15,14,7])
# 使用正确的修改方式
obj.changeRating_correct("sushi", 16)
# 此时,"sushi"的评分已更新,并在SortedSet中重新排序
# 可以验证最高评分食物是否正确
# print(obj.highestRated("japanese")) # 预期输出 "ramen" (14), 因为sushi (16)现在最高在这个正确的实现中:
遵循这些原则,可以有效避免在使用SortedSet等高级数据结构时遇到的潜在问题,确保程序的健壮性和正确性。
以上就是SortedSet中元素键值修改的陷阱与正确实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号