我知道
dict
中的键没有顺序(即使它们在最近的实现中保留了插入顺序,正如我在 CPython 核心开发人员 Hettinger 的视频中看到的那样,但这超出了主题)。
Python 中是否有一种数据结构,其行为类似于
dict
,但其 的键顺序可以自定义,并且保证顺序被保留?(例如在 pickle
转储 + 加载等之后) .)
collections.OrderedDict
似乎是一个不错的候选者,但最终不是,因为我们无法完全自定义按键的顺序,而只能移动到开头或结尾:move_to_end
。
从 Python 3.6 开始,字典数据结构被替换为保存插入顺序。
如果你想使用内置结构,可以使用priorityqueue,这样你就可以根据自己的情况来决定顺序了。
import math
from queue import PriorityQueue
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
@staticmethod
def of(x, y):
return Point(x, y)
def __str__(self):
return f"Point: x:{self.x} y:{self.y}"
def get_distance(self, other):
return math.sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2)
# Example usage
my_point = Point.of(9, 2)
point_array = [Point(1, 5), Point(5, 65), Point(9, 2)]
queue = PriorityQueue()
for point in point_array:
queue.put((point.get_distance(my_point), point))
while not queue.empty():
distance, point = queue.get()
print(point)
在此示例中,我创建了一个 PriorityQueue,以便根据受访者到 my_point 的距离对它们进行排序。