[英]Pythonic Way of Lexicographically Sorting Keys of an OrderedDict On Insert
我有以下 class 跟踪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() )
Output /Austin:-123 /James:600 /Justin:1
我有点困惑。 听起来您指的是 sortedcollections 模块中的 OrderedDict class ; 该模块还包含您要查找的内容,即 SortedDict。 通常, sortedcollections 模块包含许多容器,可以有效地使用大型列表和字典。 例如,对于普通的 python dict(),在 SortedDict 中的查找时间是 O(log(n)) 而不是 O(n)。
from sortedcollections import SortedDict
D = SortedDict([("/James",600),("/Justin",1),("/Austin",-123)])
print(D)
一般来说,SortedDict 和 SortedList 可以保存数百万个值,但会立即查找值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.