OrderedDict 没有保持秩序 [英] OrderedDict not staying in order

查看:48
本文介绍了OrderedDict 没有保持秩序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个循环的想法是遍历一个列表.如果对象的某个属性不是 OrderedDict 的键,它会添加它.它是一个对象列表字典

The idea of this loop was to iterate through a list. If a certain property of an object was not a key of the OrderedDict, it would add it. It is a dictionary of lists of objects

for object in someList:
  if object.DATE not in myOrderedDict:
     myOrderedDict[object.DATE]=[]
  myOrderedDict[object.DATE].append(object)

虽然它似乎确实使 OrderedDict 基本正确,但它在打印时最终会乱序.而不是像 (01/13) (02/13) (03/13) 它更像是 (02/13) (03/13) (01/13).
为什么会发生这种情况,如何解决?

while it does seem to make the OrderedDict mostly correctly, it ends up out of order when it's printed. Instead of having something like (01/13) (02/13) (03/13) it goes more like (02/13) (03/13) (01/13).
Why does this happen and how can it be fixed?

推荐答案

您似乎希望 OrderedDict 中的项目按关键字排序,但事实并非如此.OrderedDict 由添加到其中的订单项排序.来自 PEP 372 常见问题解答:

It would appear that you expect the items in an OrderedDict to be ordered by key, which is not the case. An OrderedDict is ordered by the order items are added to it. From the PEP 372 FAQ:

OrderedDict 是否支持替代排序顺序,例如字母顺序?

没有.那些想要不同排序顺序的人确实需要使用另一种技术.OrderedDict 是关于记录插入顺序的.如果对任何其他顺序感兴趣,那么另一个结构(如内存中的 dbm)可能更适合.

No. Those wanting different sort orders really need to be using another technique. The OrderedDict is all about recording insertion order. If any other order is of interest, then another structure (like an in-memory dbm) is likely a better fit.

这篇关于OrderedDict 没有保持秩序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆