如何将元组的python列表转换为树?

时间:2016-09-14 16:57:21

标签: python algorithm tree binary-search-tree

我有一个像

这样的元组列表
list_of_tuples = [(number, name, id, parent_id),
     (number, name, id, parent_id),
    ]

我正在尝试将其排序为有序结构,如:

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

因此,任何节点都可以拥有父节点和/或子节点 我尝试过:

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)

但是当节点同时拥有父级和子级

时,我正在失去深层次结构

如何正确订购?

1 个答案:

答案 0 :(得分:1)

我建议将树节点表示为元组((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