我试图将以下代码从PHP翻译成Python。该代码旨在展平json树结构。你能帮我把它翻译成一个等价的Python函数吗?
function flatten($parent,&$return,$stack=[]){
foreach($parent as $child){
$return[]=array_merge($stack,[$child->name]);
}
}
$json=json_decode(file_get_contents('tmpfile.json'));
$root=$json->report->data;
$return=[];
flatten($root,$return);
print_r($return);
自问题解决以来,在Python中回答:
def flatten_two(parent, _return, stack = []):
for child in parent:
if 'breakdown' in child:
flatten_two(child['breakdown'], _return, stack + [child['name']] )
else:
_return.append(stack + [child['name'], child['counts'][0]])
_return_list = []
flatten_two(report_data, _return_list)
print(_return_list)
答案 0 :(得分:1)
类似于:
import json
def flatten(x):
if isinstance(x, list):
return [a for i in x for a in flatten(i)]
else:
return [x]
json.dumps(flatten(LoL))
LoL
是json'd之前要展平的列表列表
或者,如果您从JSON开始:
flatten(json.loads('[1, 2, [3, 4, [5], ["nested"]], [6, [[[7, "deeper"]]]]]'))