python - 在插入时对 OrderedDict 的键进行字典排序的 Pythonic 方式
问题描述
我有以下课程可以跟踪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
解决方案
我有点困惑。听起来您指的是 sortedcollections 模块中的 OrderedDict 类;该模块还包含您要查找的内容,即 SortedDict。通常, sortedcollections 模块包含许多容器,可以有效地使用大型列表和字典。例如,在 SortedDict 中查找时间是 O(log(n)) 而不是普通 python dict() 的 O(n)。
from sortedcollections import SortedDict
D = SortedDict([("/James",600),("/Justin",1),("/Austin",-123)])
print(D)
一般来说,SortedDict 和 SortedList 可以保存数百万个值,但会立即查找值。
推荐阅读
- android - 从普通 Skype 应用程序呼叫 Skype for business 帐户
- java - 如何使用 Selenium Webdriver 从 Angular 应用程序中获取所有 WebElement?
- linux - 获取 bash 脚本以打开终端
- laravel - 注册用户后如何在laravel应用程序中验证用户手机号码?
- c# - 在文件中查找包含特定单词的行,例如 assert、Assert、ASSERTION,而不是组合单词,例如 assertCount assert_Count
- node.js - 使用 express 初始化 ws 服务器
- java - 开发者!不适用于 Eclipse.app 或 SpringToolSuite4.app(在 Mac 上)
- autodesk-forge - 保留策略持续存在时如何访问存储桶?
- javascript - 如何访问 indexDb 变量并访问该变量?
- graphql - 有没有办法将参数传递给 GraphQL 查询以指定它应该运行的 GraphQL 类型?