How to convert python list of tuples into tree?

大兔子大兔子 提交于 2019-12-10 10:27:09

问题


I have a list of tuples like

list_of_tuples = [(number, name, id, parent_id),
     (number, name, id, parent_id),
    ]

I am trying to sort it into an ordered structure like:

{
    parent: [(id, name), (id, name)],
    parent: {parent: [(id, name)]
{

So, any node could have a parent and/or children I tried with:

tree = defaultdict(lambda: [None, ()])
ancestors = set([item[3] for item in list_of_tuples])

for items in list_of_tuples:
    children_root = {}
    descendants = []
    number, name, id, parent = items
    if parent is None:
        tree[id] = [(id, name)]
    elif parent:
        if parent not in tree.keys():
            node = tree.get(parent)
            node.append((id, name))
        children = (id, name)
        tree[parent].append(children)

But I'm losing deep hierarchy when a node has both a parent and children

How do I make the ordering work correctly?


回答1:


I propose to represent the tree nodes as tuples ((id, name), dict_of_children).

list_of_tuples = [(1, 'name1', 1, None),
     (2, 'name2', 2, 1),
     (3, 'name3', 3, 1),
     (4, 'name4', 4, 2),
     (5, 'name5', 5, 2),
     (6, 'name5', 6, None),
     (7, 'name5', 7, 6),
    ]

def build_tree(list_of_tuples):
    """
    >>> import pprint
    >>> pprint.pprint(build_tree(list_of_tuples))
    {1: ((1, 'name1'),
         {2: ((2, 'name2'), {4: ((4, 'name4'), {}), 5: ((5, 'name5'), {})}),
          3: ((3, 'name3'), {})}),
     6: ((6, 'name5'), {7: ((7, 'name5'), {})})}
    """
    all_nodes = {n[2]:((n[2], n[1]), {}) for n in list_of_tuples}
    root = {}
    for item in list_of_tuples:
        number, name, id, parent = item
        if parent is not None:
            all_nodes[parent][1][id] = all_nodes[id]
        else:
            root[id] = all_nodes[id]
    return root


来源:https://stackoverflow.com/questions/39495924/how-to-convert-python-list-of-tuples-into-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!