【发布时间】: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 或者使用
bisectlib... -
@JonClements 是的,我认为这实际上更好
标签: python python-3.x sorting dictionary ordereddictionary