gpt4 book ai didi

python - OrderedDict 未订购?

转载 作者:IT老高 更新时间:2023-10-28 22:19:42 27 4
gpt4 key购买 nike

我正在尝试使用 OrderedDict,但它一直被乱序创建。例如,

from collections import OrderedDict
OrderedDict(a=1,b=2,c=3)

产量

OrderedDict([('a', 1), ('c', 3), ('b', 2)])

而不是预期

OrderedDict([('a', 1), ('b', 2), ('c', 3)])

如何确保它按照我想要的正确顺序创建?

最佳答案

collections.OrderedDict 跟踪添加元素的顺序。这将在循环中正常工作:

c = collections.OrderedDict()
for a,b in zip('abc', (1,2,3)):
c[a] = b

但是,表达式 OrderedDict(a=1,b=2,c=3) 通过将几个关键字参数传递给它的构造函数来创建一个 OrderedDict。在 Python 2.7 中,不保证关键字参数的顺序。如果你想这样做,你将不得不迁移到 Python 3.6,它实现了 PEP 468,Preserving the order of **kwargs in a function .

The **kwargs syntax in a function definition indicates that the interpreter should collect all keyword arguments that do not correspond to other named parameters. However, Python does not preserved the order in which those collected keyword arguments were passed to the function. In some contexts the order matters. This PEP dictates that the collected keyword arguments be exposed in the function body as an ordered mapping.

关于python - OrderedDict 未订购?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41866911/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com