您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python-从元组列表生成字典(树)

Python-从元组列表生成字典(树)

这是一个更简单的方法。(根据我从托马斯答案中了解到的那样进行编辑,可以按任意顺序指定节点):第1遍创建节点(即,将它们添加到节点字典中),而第2遍然后创建parent <-> children结构。

进行以下假设:没有循环(由Garret R指出,在这种情况下尚不清楚预期的输出是什么),没有丢失的边,没有丢失的树根。

a = [(1, 1), (2, 1), (3, 1), (4, 3), (5, 3), (6, 3), (7, 7), (8, 7), (9, 7)]

# pass 1: create nodes dictionary
nodes = {}
for i in a:
    id, parent_id = i
    nodes[id] = { 'id': id }

# pass 2: create trees and parent-child relations
forest = []
for i in a:
    id, parent_id = i
    node = nodes[id]

    # either make the node a new tree or link it to its parent
    if id == parent_id:
        # start a new tree in the forest
        forest.append(node)
    else:
        # add new_node as child to parent
        parent = nodes[parent_id]
        if not 'children' in parent:
            # ensure parent has a 'children' field
            parent['children'] = []
        children = parent['children']
        children.append(node)

print forest

编辑:为什么您的解决方案无法按预期工作?

这是有关顶层的提示:您要获取输出是树 列表 。但是,要处理的变量(d)必须是字典,因为在函数set_nested中,您将setdefaults方法应用于该变量。

python 2022/1/1 18:45:21 有480人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶