这是我拥有的数据结构
[{
"tree": [{
"tree": [{
"name": "Dinosaur Rex",
"key": "Dinosaur Rex"
}, {
"name": "hats",
"key": "hats"
}],
"name": "Plugin1",
"key": "Plugin1"
}],
"name": "Plugins",
"key": "plugins"
}, {
"tree": [{
"key": "memSwapFree",
"name": "Swap free",
"unit": "MB"
}, {
"key": "memPhysUsed",
"name": "Physical used",
"unit": "MB"
}, {
"key": "memSwapUsed",
"name": "Swap used",
"unit": "MB"
}, {
"key": "memPhysFree",
"name": "Physical free",
"unit": "MB"
}],
"name": "Memory",
"key": "memory"
}]
我想输出下面的内容。我很难想出一个很好的方法。
[
['plugins', 'plugin1', 'hats'],
['plugins', 'plugin1', 'Dinosaur Rex']
['memory', 'memPhysFree'],
['memory', 'memSwapFree'],
['memory', 'memPhysUsed'],
['memory', 'memSwapUsed'],
]
答案 0 :(得分:1)
使用递归生成器并不难,提取"key"
值:
def flatten(lst):
for dct in lst:
key = dct["key"]
if "tree" not in dct:
yield [key] # base case
else:
for result in flatten(dct["tree"]): # recursive case
yield [key] + result
如果您需要实际列表,请拨打list(flatten(list_of_dicts))
。