【问题标题】:How to keep a dict sorted as new items are pushed in?如何在推入新项目时保持字典排序?
【发布时间】:2018-02-11 14:50:35
【问题描述】:

所以我有一个这样的高分文件:

Markus:5000
Mike:3000
John:2400

我把它读给OrderdDict

high_scores = OrderedDict()
with open('highscores.txt') as file:
    for line in file:
        name, score = line.strip().split(':')
        high_scores[name] = int(score)

现在,当我向字典中添加新分数时,如何保持排序?我想到的唯一方法是每次都用这样的东西重新创建字典:

high_scores = sorted(high_scores.items(), key=lambda x: x[1], reversed=True)
high_scores = OrderedDict(high_scores)

但这似乎是相当糟糕的行为,我更希望在将元素添加到字典时将它们放入正确的位置,即我希望始终保持字典排序。

【问题讨论】:

  • 如果您想保留排序顺序,您可能需要考虑另一种数据结构,例如优先级队列。
  • sort每次可能并不像听起来那么糟糕,因为算法 timsort 的工作方式,也是在 C 中完成的,但sort 像 John 建议的列表代替
  • @Chris_Rands 或者使用bisect lib...
  • @JonClements 是的,我认为这实际上更好

标签: python python-3.x sorting dictionary ordereddictionary


【解决方案1】:

OrderedDict 不是高分列表的最佳结构。尝试使用 2 元组的常规列表,每次添加元素时只需 sort() 即可。

如果你真的不喜欢显式排序,你可以使用https://pypi.python.org/pypi/sortedcontainers 为你做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-02
    • 2015-09-03
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多