4 つのレベルを持つ yaml 構成ファイルから返された辞書があります。
アイテム、セクション、フィールド、要素
{
"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
したがって、辞書のリストを持つ辞書のリストの辞書を再帰する必要があります。など、それらをタイプに分類し (そして、それが属する部分への参照を追加しますが、一度に 1 つの問題を追加します)、T のインスタンスに入れます。
これは機能しますが、何も削除しません。つまり、各セクションがキャプチャされますが、残りのすべて (フィールド、要素) がキャプチャされます。これはおそらくcomp sci 101ですが、私はほとんど独学なので、このある種のソートアルゴリズムについて学ぶ必要があります。これを改善するためのご意見をお待ちしております。
編集:これは私が予想したよりも詳細であることが判明し、抽象的には、任意のデータ構造を調べて、必要なものまたは必要なものを選択する方法を学ぶ機会が増えました