簡體   English   中英

在插入時對 OrderedDict 的鍵進行字典排序的 Pythonic 方式

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM