【发布时间】:2021-05-12 20:28:41
【问题描述】:
我有一个跟踪OrderedDict的类:
class LexDict:
def __init__(self):
self.m_map = OrderedDict() # maps string which is case-sensitive to int
def set(self,id,seqNo):
self.m_map[id] = seqNo
def get(self,id): # seqNo returned
return self.m_map[id] if self.has(id) else 0
def has(self,id): # bool value
return ( id in self.m_map.keys() )
def to_str(self):
stream = ""
for key,value in self.m_map.items():
stream = stream + key + ":" + str(value) + " "
return stream.rstrip()
我的目标是更改 set() 方法,使其始终按字典顺序排列,这样无论何时调用 to_str(),它都将按字典顺序排列。我们可以放心地假设此字典中的映射不会被删除。这将用于网络情况,因此效率是关键,对整个列表进行排序而不是将其移动到正确的位置会损害性能。
如何使用它的示例。
a = LexDict()
a.set("/Justin",1) # the id will have "/"s (maybe even many) in it, we can image them without "/"s for sorting
a.set("/James",600)
a.set("/Austin",-123)
print( a.to_str() )
输出/Austin:-123 /James:600 /Justin:1
【问题讨论】:
-
您的问题到底是什么?此外,与其发明自定义 API,不如将其设为
MutableMapping,这样您就可以真正将其用作字典替代品了? -
有序字典只记得插入顺序。您必须跟踪词汇顺序,例如在单独的列表中。因此,您可以创建一个按词汇顺序保存 ID 的列表。在每次插入时,您都会找到插入点(例如通过二叉树搜索)并在相应的列表位置添加 ID。
标签: python python-3.x dictionary ordereddictionary lexicographic