使用Python转换具有“level”列的数据。

huangapple go评论74阅读模式
英文:

Transform data with level column in python

问题

这是您所提供的数据,表示分层树结构:

[
    {
        "level": 0,
        "name": "python"
    },
    {
        "level": 1,
        "name": "food"
    },
    {
        "level": 2,
        "name": "banana"
    },
    {
        "level": 3,
        "name": "protein"
    },
    {
        "level": 2,
        "name": "apple"
    },
    {
        "level": 1,
        "name": "fuel"
    }
]

我想要将其转换为以下结构:

[
    {
        "level": 0,
        "name": "python",
        "children": [
            {
                "level": 1,
                "name": "food",
                "children": [
                    {
                        "level": 2,
                        "name": "banana",
                        "children": [
                            {
                                "level": 3,
                                "name": "protein",
                                "children": [

                                ]
                            }
                        ]
                    },
                    {
                        "level": 2,
                        "name": "apple",
                        "children": [

                        ]
                    }
                ]
            },
            {
                "level": 1,
                "name": "fuel",
                "children": [

                ]
            }
        ]
    }
]

我使用Python,希望在Python中提供解决方案,无论是否使用外部库(包括pandas)。期待您的解决方案,提前感谢!

英文:

I have data like this which represents hierarchical tree structure:

[
    {
        "level":0,
        "name":"python"
    },
    {
        "level":1,
        "name":"food"
    },
    {
        "level":2,
        "name":"banana"
    },
    {
        "level":3,
        "name":"protein"
    },
    {
        "level":2,
        "name":"apple"
    },
    {
        "level":1,
        "name":"fuel"
    }
]

I want to transform it into:

[
    {
        "level":0,
        "name":"python",
        "children":[
            {
                "level":1,
                "name":"food",
                "children":[
                    {
                        "level":2,
                        "name":"banana",
                        "children":[
                            {
                                "level":3,
                                "name":"protein",
                                "children":[
                                    
                                ]
                            }
                        ]
                    },
                    {
                        "level":2,
                        "name":"apple",
                        "children":[
                            
                        ]
                    }
                ]
            },
            {
                "level":1,
                "name":"fuel",
                "children":[
                    
                ]
            }
        ]
    }
]

I am using python and would prefer the solution in python with or without using external libraries, (even using pandas). I would love to see the solutions, thank you in advance 使用Python转换具有“level”列的数据。

答案1

得分: 1

以下是代码部分的中文翻译:

def create_tree(nodes):
    # 为每个节点添加父节点信息
    for i, node in enumerate(nodes):
        if node['level'] == 0:
            node['parent'] = None
        else:
            j = i - 1
            while j >= 0:
                if nodes[j]['level'] < node['level']:
                    node['parent'] = nodes[j]['name']
                    break
                j -= 1

    node_dict = {}
    for node in nodes:
        node_dict[node['name']] = node

    for node in nodes:
        parent_name = node.get('parent')
        if parent_name is not None:
            parent = node_dict[parent_name]
            if 'children' not in parent:
                parent['children'] = []
            parent['children'].append(node)

    for node in nodes:
        if node.get('parent') is None:
            return node
    return None

nodes = [
    {"level": 0, "name": "python"},
    {"level": 1, "name": "food"},
    {"level": 2, "name": "banana"},
    {"level": 3, "name": "protein"},
    {"level": 2, "name": "apple"},
    {"level": 1, "name": "fuel"}
]

tree = create_tree(nodes)

print(tree)

这是你所需的代码。

英文:

Here is one way:

def create_tree(nodes):
    # add parent information to each node
    for i, node in enumerate(nodes):
        if node[&#39;level&#39;] == 0:
            node[&#39;parent&#39;] = None
        else:
            j = i - 1
            while j &gt;= 0:
                if nodes[j][&#39;level&#39;] &lt; node[&#39;level&#39;]:
                    node[&#39;parent&#39;] = nodes[j][&#39;name&#39;]
                    break
                j -= 1
    
    
    node_dict = {}
    for node in nodes:
        node_dict[node[&#39;name&#39;]] = node
    
    for node in nodes:
        parent_name = node.get(&#39;parent&#39;)
        if parent_name is not None:
            parent = node_dict[parent_name]
            if &#39;children&#39; not in parent:
                parent[&#39;children&#39;] = []
            parent[&#39;children&#39;].append(node)
    
    for node in nodes:
        if node.get(&#39;parent&#39;) is None:
            return node
    return None

nodes = [
    {&quot;level&quot;:0,&quot;name&quot;:&quot;python&quot;},
    {&quot;level&quot;:1,&quot;name&quot;:&quot;food&quot;},
    {&quot;level&quot;:2,&quot;name&quot;:&quot;banana&quot;},
    {&quot;level&quot;:3,&quot;name&quot;:&quot;protein&quot;},
    {&quot;level&quot;:2,&quot;name&quot;:&quot;apple&quot;},
    {&quot;level&quot;:1,&quot;name&quot;:&quot;fuel&quot;}
]

tree = create_tree(nodes)

print(tree)


which gives what you wanted

{&#39;level&#39;: 0, &#39;name&#39;: &#39;python&#39;, &#39;parent&#39;: None, &#39;children&#39;: [{&#39;level&#39;: 1, &#39;name&#39;: &#39;food&#39;, &#39;parent&#39;: &#39;python&#39;, &#39;children&#39;: [{&#39;level&#39;: 2, &#39;name&#39;: &#39;banana&#39;, &#39;parent&#39;: &#39;food&#39;, &#39;children&#39;: [{&#39;level&#39;: 3, &#39;name&#39;: &#39;protein&#39;, &#39;parent&#39;: &#39;banana&#39;}]}, {&#39;level&#39;: 2, &#39;name&#39;: &#39;apple&#39;, &#39;parent&#39;: &#39;food&#39;}]}, {&#39;level&#39;: 1, &#39;name&#39;: &#39;fuel&#39;, &#39;parent&#39;: &#39;python&#39;}]}

答案2

得分: 1

以下是代码部分的翻译:

我想你的列表中字典的顺序很重要否则我将不知道子元素应该在哪个父元素下列出我建议编写一个递归函数以获取在第 n 级的最后一个元素并将子元素附加在那里

input_list = [
    {
        "level": 0,
        "name": "python"
    },
    {
        "level": 1,
        "name": "food"
    },
    {
        "level": 2,
        "name": "banana"
    },
    {
        "level": 3,
        "name": "protein"
    },
    {
        "level": 2,
        "name": "apple"
    },
    {
        "level": 1,
        "name": "fuel"
    }
]

def get_last_elt_at_lvl(rec, lvl):
    if lvl == 0:
        return rec[-1]
    else:
        for i in range(len(rec)-1,-1,-1):
            if rec[i]['children']:
                r = get_last_elt_at_lvl(rec[-1]['children'], lvl-1)
                if r:
                    return r
    return None

output_list = []
for d in input_list:
    if d["level"] == 0:
        output_list.append(d)
    else:
        last_elt = get_last_elt_at_lvl(output_list, d["level"]-1)
        children = last_elt.setdefault('children', [])
        children.append(d)

print(json.dumps(output_list, indent=4))

输出结果:

[
    {
        "level": 0,
        "name": "python",
        "children": [
            {
                "level": 1,
                "name": "food",
                "children": [
                    {
                        "level": 2,
                        "name": "banana",
                        "children": [
                            {
                                "level": 3,
                                "name": "protein"
                            }
                        ]
                    },
                    {
                        "level": 2,
                        "name": "apple"
                    }
                ]
            },
            {
                "level": 1,
                "name": "fuel"
            }
        ]
    }
]

希望这对你有所帮助!

英文:

I suppose the order of the dictionaries in your list matters, since otherwise I wouldn't know under which parent the children are supposed to be listed. I would suggest to write a recursive function to get the last element at level n and append the children there:

import json

input_list = [
    {
        &quot;level&quot;:0,
        &quot;name&quot;:&quot;python&quot;
    },
    {
        &quot;level&quot;:1,
        &quot;name&quot;:&quot;food&quot;
    },
    {
        &quot;level&quot;:2,
        &quot;name&quot;:&quot;banana&quot;
    },
    {
        &quot;level&quot;:3,
        &quot;name&quot;:&quot;protein&quot;
    },
    {
        &quot;level&quot;:2,
        &quot;name&quot;:&quot;apple&quot;
    },
    {
        &quot;level&quot;:1,
        &quot;name&quot;:&quot;fuel&quot;
    }
]

def get_last_elt_at_lvl(rec, lvl):
    if lvl == 0:
        return rec[-1]
    else:
        for i in range(len(rec)-1,-1,-1):
            if rec[i][&#39;children&#39;]:
                r = get_last_elt_at_lvl(rec[-1][&#39;children&#39;], lvl-1)
                if r:
                    return r
    return None

output_list = []
for d in input_list:
    if d[&quot;level&quot;] == 0:
        output_list.append(d)
    else:
        last_elt = get_last_elt_at_lvl(output_list, d[&quot;level&quot;]-1)
        children = last_elt.setdefault(&#39;children&#39;, [])
        children.append(d)

print(json.dumps(output_list, indent=4))

Output:

[
    {
        &quot;level&quot;: 0,
        &quot;name&quot;: &quot;python&quot;,
        &quot;children&quot;: [
            {
                &quot;level&quot;: 1,
                &quot;name&quot;: &quot;food&quot;,
                &quot;children&quot;: [
                    {
                        &quot;level&quot;: 2,
                        &quot;name&quot;: &quot;banana&quot;,
                        &quot;children&quot;: [
                            {
                                &quot;level&quot;: 3,
                                &quot;name&quot;: &quot;protein&quot;
                            }
                        ]
                    },
                    {
                        &quot;level&quot;: 2,
                        &quot;name&quot;: &quot;apple&quot;
                    }
                ]
            },
            {
                &quot;level&quot;: 1,
                &quot;name&quot;: &quot;fuel&quot;
            }
        ]
    }
]

huangapple
  • 本文由 发表于 2023年2月23日 23:53:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75547223.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定