OrderedDict 不是有序的吗? [英] OrderedDict Isn't Ordered?

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

问题描述

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

I'm trying to use an OrderedDict, but it keeps being created out of order. For example,

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)])

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

How can I make sure it's created in the proper order I intend?

推荐答案

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

collections.OrderedDict keeps track of the order in which elements were added to it. This would work fine in a loop:

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,保留 * 的顺序*函数中的kwargs.

However, the expression OrderedDict(a=1,b=2,c=3) creates an OrderedDict by passing several keyword arguments to its constructor. In Python 2.7, the order of keyword arguments is not guaranteed. If you want that, you'll have to move to Python 3.6, which implements PEP 468, Preserving the order of **kwargs in a function.

函数定义中的 **kwargs 语法表明解释器应该收集所有与其他命名参数不对应的关键字参数.但是,Python 不会保留这些收集的关键字参数传递给函数的顺序.在某些情况下,顺序很重要.此 PEP 规定收集的关键字参数在函数体中作为有序映射公开.

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.

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

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