Input data = [1,12,122,14] .
Output data =
{
"1": {
"children": [
{
"12": {
"children": [
{
"122": {
"children": []
}
}
]
}
},
{
"14": {
"children": []
}
}
]
}
}
这似乎与尝试有一些关系,我能够在输入中生成python中的trie。
答案 0 :(得分:1)
您可以使用递归,并创建深度限制以确定何时开始将新节点收集到单个列表中:
def trie(d, current = 0, depth = 2):
if len(d) == len(data):
return {d[0]:{'children':filter(None, [trie(d[1:]), {d[-1]:{'children':[]}}])}}
if current == depth:
return [{i:{'children':[]}} for i in d]
return {d[0]:{'children':trie(d[1:], current+1)}}
new_data = [[1,12,122,14], [1,12,122,123,14], [1,14,16,12,122,123]]
new_list = [trie(sorted(i, key=lambda x:str(x))) for i in new_data]
输出:
[{1: {'children': {12: {'children': [{122: {'children': []}}, {14: {'children': []}}]}}}}, {1: {'children': {12: {'children': [{122: {'children': []}}, {123: {'children': []}}, {14: {'children': []}}]}}}}, {1: {'children': [{12: {'children': {122: {'children': [{123: {'children': []}}, {14: {'children': []}}, {16: {'children': []}}]}}}}, {16: {'children': []}}]}}]