Python OrderedDict 不保持元素顺序 [英] Python OrderedDict not keeping element order
问题描述
我正在尝试创建一个 OrderedDict 对象,但我刚创建它,元素就变得混乱了.
这就是我所做的:
from collections import OrderedDictod = OrderedDict({(0,0):[2],(0,1):[1,9],(0,2):[1,5,9]})
元素没有按照我指定的顺序保持
odOrderedDict([((0, 1), [1, 9]), ((0, 0), [2]), ((0, 2), [1, 5, 9])])
docs.python.org 没有示例,我无法弄清楚为什么订单会变得混乱.任何帮助是极大的赞赏.
您的问题是您正在构建一个 dict
以将初始数据提供给 OrderedDict
- 这dict
不存储任何订单,因此订单在到达OrderedDict
之前就丢失了.
解决方案是从有序数据类型构建 - 最简单的是 tuple
的 list
:
值得注意的是,这就是 OrderedDict
使用它为字符串表示所做的语法的原因 - 字符串表示应该尝试成为有效的 Python 代码以在可能的情况下重现对象,这就是为什么输出使用元组列表而不是字典.
从 Python 3.6 开始, kwargs
是有序的,因此您可以使用关键字参数代替,前提是您使用的是最新的 Python 版本.
从 3.7 开始,对于 dict<也是如此/code>s(它在 3.6 中用于 CPython,但语言规范没有指定它,因此为了兼容性仍然需要使用
OrderedDict
).这意味着如果您可以假设 3.7+ 环境,您通常可以完全删除 OrderedDict
,或者如果您需要特定功能(例如:订购到平等的问题).
I'm trying to create an OrderedDict object but no sooner do I create it, than the elements are all jumbled.
This is what I do:
from collections import OrderedDict
od = OrderedDict({(0,0):[2],(0,1):[1,9],(0,2):[1,5,9]})
The elements don't stay in the order I assign
od
OrderedDict([((0, 1), [1, 9]), ((0, 0), [2]), ((0, 2), [1, 5, 9])])
docs.python.org doesn't have an example and I can't figure out why the order is getting jumbled. Any help is greatly appreciated.
Your problem is that you are constructing a dict
to give the initial data to the OrderedDict
- this dict
doesn't store any order, so the order is lost before it gets to the OrderedDict
.
The solution is to build from an ordered data type - the easiest being a list
of tuple
s:
>>> from collections import OrderedDict
>>> od = OrderedDict([((0, 0), [2]), ((0, 1), [1, 9]), ((0, 2), [1, 5, 9])])
>>> od
OrderedDict([((0, 0), [2]), ((0, 1), [1, 9]), ((0, 2), [1, 5, 9])])
It's worth noting that this is why OrderedDict
uses the syntax it does for it's string representation - string representations should try to be valid Python code to reproduce the object where possible, and that's why the output uses a list of tuples instead of a dict.
Edit: As of Python 3.6, kwargs
is ordered, so you can use keyword arguments instead, provided you are on an up-to-date Python version.
As of 3.7, this is also true for dict
s (it was for CPython in 3.6, but the language spec didn't specify it, so using OrderedDict
was still required for compatibility). This means if you can assume a 3.7+ environment, you can often drop OrderedDict
altogether, or construct one from a regular dict
if you need a specific feature (e.g: order to matter for equality).
这篇关于Python OrderedDict 不保持元素顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!