nei*_*kin 30 python ordereddictionary
为什么我的python OrderedDict被初始化为'乱序'?
这里的解决方案不如解释那么有趣.这里有些东西,我只是没有得到,也许扩张会帮助别人和我.
>>> from collections import OrderedDict
>>> spam = OrderedDict(s = (1, 2), p = (3, 4), a = (5, 6), m = (7, 8))
>>> spam
OrderedDict([('a', (5, 6)), ('p', (3, 4)), ('s', (1, 2)), ('m', (7, 8))])
>>> for key in spam.keys():
... print key
...
# this is 'ordered' but not the order I wanted....
a
p
s
m
# I was expecting (and wanting):
s
p
a
m
Run Code Online (Sandbox Code Playgroud)
Chr*_*cho 37
来自文档:
OrderedDict构造函数和
update()方法都接受关键字参数,但它们的顺序丢失,因为Python的函数使用常规无序字典调用语义传入关键字参数.
所以初始化会失去排序,因为它基本上是用一个构造函数来调用的**kwargs.
编辑:就解决方案而言(不仅仅是解释) - 如OP的评论所指出的那样,传入单个元组列表将起作用:
>>> from collections import OrderedDict
>>> spam = OrderedDict([('s',(1,2)),('p',(3,4)),('a',(5,6)),('m',(7,8))])
>>> for key in spam:
... print(key)
...
s
p
a
m
>>> for key in spam.keys():
... print(key)
...
s
p
a
m
Run Code Online (Sandbox Code Playgroud)
这是因为它只获得一个参数,一个列表.
Pad*_*118 17
@Chris Krycho很好地解释了为什么失败了.
如果你查看OrderedDict的repr(),你会得到一个如何从头开始传递顺序的提示:你需要使用(键,值)对的列表来保持列表给出的键的顺序.
这是我之前做的一个:
>>> from collections import OrderedDict
>>> spamher = OrderedDict(s=6, p=5, a=4, m=3, h=2, e=1, r=0)
>>> spamher
OrderedDict([('h', 2), ('m', 3), ('r', 0), ('s', 6), ('p', 5), ('a', 4), ('e', 1)])
>>>
>>> list(spamher.keys())
['h', 'm', 'r', 's', 'p', 'a', 'e']
>>>
>>> spamher = OrderedDict([('s', 6), ('p', 5), ('a', 4), ('m', 3), ('h', 2), ('e', 1), ('r', 0)])
>>> list(spamher.keys())
['s', 'p', 'a', 'm', 'h', 'e', 'r']
>>>
Run Code Online (Sandbox Code Playgroud)
(事实恰恰相反,在Python v3.3.0中,您的原始示例spam从一开始就将密钥保持在原始顺序中.我改为spamher了解这个问题).
| 归档时间: |
|
| 查看次数: |
40022 次 |
| 最近记录: |