我有一个有点复杂的数据结构:有序字典的默认有序字典,遵循编码here。该类工作正常,因为如果缺少键,我可以默认创建有序词典。我想进一步扩展这个类的功能,并覆盖__iter__
方法,以便我只能迭代某个键的有序字典。也就是说,如果我有
import sys
import numpy as np
from collections import OrderedDict
class OrderedDefaultdict(OrderedDict):
def __init__(self, *args, **kwargs):
self.d = None
if not args:
self.default_factory = None
else:
if not (args[0] is None or callable(args[0])):
raise TypeError('first argument must be callable or None')
self.default_factory = args[0]
args = args[1:]
super(OrderedDefaultdict, self).__init__(*args, **kwargs)
def __iter__(self):
for k in self[self.d].values():
yield k
def __call__(self, key):
self.d = key
return self
def __missing__ (self, key):
self.d = max(self.d, key) if self.d else key
if self.default_factory is None:
raise KeyError(key)
self[key] = default = self.default_factory()
return default
def __reduce__(self): # optional, for pickle support
args = (self.default_factory,) if self.default_factory else ()
return self.__class__, args, None, None, self.iteritems()
Tree = lambda: OrderedDefaultdict(Tree)
您看到代码将最大键保存在变量self.d
中,并且我希望默认迭代其对应的字典。
def main(argv=()):
tree = Tree()
tree[0]['n1'] = np.array([[3]])
tree[1]['l2'] = np.array([[ 0, 4],
[ 4, 5],
[40, 41],
[41, 42],
[57, 3],
[57, 3]])
tree[2]['t3x'] = np.array([[188, 401, 400],
[188, 187, 401],
[187, 205, 401],
[324, 306, 417],
[306, 305, 417],
[305, 416, 417]])
tree[2]['q3'] = np.array([[188, 401, 400, 0],
[188, 187, 401, 0],
[187, 205, 401, 0],
[323, 324, 417, 0],
[324, 306, 417, 0],
[306, 305, 417, 0],
[305, 416, 417, 0]])
for el in tree:
print(el)
return 0
if __name__ == "__main__":
sys.exit(main())
在上面的代码中,我尝试迭代最高维度的字典。但是这段代码不起作用,因为我在__iter__
方法中进入无限递归,我无法理解为什么。我一直在关注如何实现这个功能的建议here。