gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:16:41 26 4
gpt4 key购买 nike

我有一个元组列表

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)

但是当节点同时具有父节点和子节点时,我将失去深层层次结构

如何使排序正常工作?

最佳答案

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

关于python - 如何将 python 元组列表转换为树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39495924/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com