我知道为了获得列表列表的组合必须使用笛卡尔积,但在我的情况下,我需要将结果作为字典,其中组合子组嵌套在里面,所以我可以将结果用作JSON用于递归角度指令,显示嵌套在N个深度级别的元素。
这是一个数据输入示例:
[
[{"cluster_id":1,"id":1,"name":"A"}, {"cluster_id":1,"id":2,"name":"B"}, {"cluster_id":1,"id":3,"name":"C"}],
[{"cluster_id":2,"id":1,"name":"D"}, {"cluster_id":2,"id":2,"name":"E"}, {"cluster_id":2,"id":3,"name":"F"}],
[{"cluster_id":3,"id":1,"name":"G"}, {"cluster_id":3,"id":2,"name":"H"}, {"cluster_id":3,"id":3,"name":"I"}]
]
这应该是这样的结果:
[{"cluster_id":1,"id":1,"name":"A", "subcluster": [
{"cluster_id":2,"id":1,"name":"D", "subcluster": [
{"cluster_id":3,"id":1,"name":"G"},
{"cluster_id":3,"id":2,"name":"H"},
{"cluster_id":3,"id":3,"name":"I"},
]
},
{"cluster_id":2,"id":2,"name":"E", "subcluster": [
{"cluster_id":3,"id":1,"name":"G"},
{"cluster_id":3,"id":2,"name":"H"},
{"cluster_id":3,"id":3,"name":"I"},
]
},
{"cluster_id":2,"id":3,"name":"F", "subcluster": [
{"cluster_id":3,"id":1,"name":"G"},
{"cluster_id":3,"id":2,"name":"H"},
{"cluster_id":3,"id":3,"name":"I"},
]
}
]
},
{"cluster_id":1,"id":2,"name":"B", "subcluster": [
{"cluster_id":2,"id":1,"name":"D", "subcluster": [
{"cluster_id":3,"id":1,"name":"G"},
{"cluster_id":3,"id":2,"name":"H"},
{"cluster_id":3,"id":3,"name":"I"},
]
},
{"cluster_id":2,"id":2,"name":"E", "subcluster": [
{"cluster_id":3,"id":1,"name":"G"},
{"cluster_id":3,"id":2,"name":"H"},
{"cluster_id":3,"id":3,"name":"I"},
]
},
{"cluster_id":2,"id":3,"name":"F", "subcluster": [
{"cluster_id":3,"id":1,"name":"G"},
{"cluster_id":3,"id":2,"name":"H"},
{"cluster_id":3,"id":3,"name":"I"},
]
}
]
},
{"cluster_id":1,"id":3,"name":"C", "subcluster": [
{"cluster_id":2,"id":1,"name":"D", "subcluster": [
{"cluster_id":3,"id":1,"name":"G"},
{"cluster_id":3,"id":2,"name":"H"},
{"cluster_id":3,"id":3,"name":"I"},
]
},
{"cluster_id":2,"id":2,"name":"E", "subcluster": [
{"cluster_id":3,"id":1,"name":"G"},
{"cluster_id":3,"id":2,"name":"H"},
{"cluster_id":3,"id":3,"name":"I"},
]
},
{"cluster_id":2,"id":3,"name":"F", "subcluster": [
{"cluster_id":3,"id":1,"name":"G"},
{"cluster_id":3,"id":2,"name":"H"},
{"cluster_id":3,"id":3,"name":"I"},
]
}
]
}]
如果可能的话,我想知道如何使用Pyhton生成此输出,但欢迎任何帮助。
答案 0 :(得分:1)
我终于能够使用以下递归函数解决它:
def generate_tree(filters, depth):
if depth == len(filters)-1:
return filters[depth]
else:
return [{'name': i['name'], 'id': i['id'], 'cycle_cluster_id': i['cycle_cluster_id'], 'subcluster': generate_tree(filters, depth+1)} for i in filters[depth]]