我有一个从 yaml 配置文件返回的字典,它有 4 个级别:
项目、部分、字段、元素
{
"tag": "test",
"sections": [
{
"info": "This is section ONE",
"tag": "s1"
},
{
"info": "This is section TWO",
"fields": [
{
"info": "This is field ONE",
"tag": "f1"
},
{
"info": "This is field TWO",
"tag": "f2",
"elements": [
{
"info": "This is element",
"tag": "e1",
"type_of": "text_field"
},
{
"info": "This is element",
"tag": "e2",
"type_of": "text_field"
},
{
"info": "This is element",
"tag": "e3",
"type_of": "text_field"
},
{
"info": "This is element",
"tag": "e4",
"type_of": "text_field"
}
]
},
{
"info": "This is field THREE",
"tag": "f3",
"elements": [
{
"info": "This is element",
"tag": "e5",
"type_of": "text_field"
},
{
"info": "This is element",
"tag": "e6",
"type_of": "text_field"
},
{
"info": "This is element",
"tag": "e7",
"type_of": "text_field"
},
{
"info": "This is element ONE",
"tag": "e8",
"type_of": "text_field"
}
]
}
],
"tag": "s2"
},
{
"info": "This is section THREE",
"fields": [
{
"info": "This is field FOUR",
"tag": "f4"
},
{
"info": "This is field FIVE",
"tag": "f5"
},
{
"info": "This is field SIX",
"tag": "f6"
}
],
"tag": "s3"
}
],
"type_of": "custom"
}
class T():
def __init__(self):
self.sections = []
self.fields = []
self.elements = []
def rt(y):
t = T()
def recurse(y):
for k,v in y.iteritems():
if isinstance(v, list):
getattr(t, k).append(v)
[recurse(i) for i in v]
else:
setattr(t, k, v)
recurse(y)
return t
所以我需要递归一个包含字典列表的字典列表等。al.,将它们分类为它们的类型(然后添加对其所属片段的引用,但一次一个问题。)并放入 T 的实例中。
这可行,但不会删除任何内容,即捕获每个部分,但捕获所有其余部分(字段、元素)。这可能是comp sci 101,但我主要是在自学,所以这是我需要学习的某种排序算法。任何关于改进这一点的意见表示赞赏。
编辑:事实证明这比我预期的更深入,并且抽象地更多的是学习如何遍历任意数据结构并挑选出我想要或需要的东西的机会