我正在尝试使用它OrderedDict,但它仍然不按顺序创建.例如,
from collections import OrderedDict
OrderedDict(a=1,b=2,c=3)
Run Code Online (Sandbox Code Playgroud)
产量
OrderedDict([('a', 1), ('c', 3), ('b', 2)])
Run Code Online (Sandbox Code Playgroud)
而不是预期的
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
Run Code Online (Sandbox Code Playgroud)
我怎样才能确保按照我想要的正确顺序创建它?
我正在使用Python 2.7.3.
考虑一个带有自定义(虽然很糟糕)迭代和项目获取行为的虚拟类:
class FooList(list):
def __iter__(self):
return iter(self)
def next(self):
return 3
def __getitem__(self, idx):
return 3
Run Code Online (Sandbox Code Playgroud)
举个例子,看看奇怪的行为:
>>> zz = FooList([1,2,3])
>>> [x for x in zz]
# Hangs because of the self-reference in `__iter__`.
>>> zz[0]
3
>>> zz[1]
3
Run Code Online (Sandbox Code Playgroud)
但现在,让我们创建一个函数,然后执行参数解包zz:
def add3(a, b, c):
return a + b + c
>>> add3(*zz)
6
# I expected either 9 or for the interpreter to hang like the comprehension!
Run Code Online (Sandbox Code Playgroud)
因此,参数解包以某种方式获取项数据,zz但不是通过使用其实现的迭代器迭代对象,也不是通过执行穷人的迭代器并调用__getitem__与对象一样多的项.
所以问题是:如果不通过这些方法,语法如何add3(*zz) …