(Python)查看父节点和子节点的列表,并按顺序显示



这是目前的列表:

my_list = [
{"name": "AAA", "parent": "none", "children": ["BBB", "CCC", "DDD"], "x": 0, "y": 0},
{"name": "BBB", "parent": "AAA", "children": ["EEE"], "x": 0, "y": 0},
{"name": "CCC", "parent": "AAA", "children": ["FFF"], "x": 0, "y": 0},
{"name": "DDD", "parent": "AAA", "children": [], "x": 0, "y": 0},
{"name": "EEE", "parent": "BBB", "children": [], "x": 0, "y": 0},
{"name": "FFF", "parent": "CCC", "children": [], "x": 0, "y": 0},
{"name": "GGG", "parent": "none", "children": ["HHH"], "x": 0, "y": 0},
{"name": "HHH", "parent": "GGG", "children": [], "x": 0, "y": 0},
]

我的期望:

AAA (0, 0)
BBB (20, 20)
EEE (40, 40)
CCC (20, 60)
FFF (40, 80)
DDD (20, 100)
GGG (0, 120)
HHH (0, 140)

我有一个列表,它的值是具有以下键的字典:& name", "parent", "children", "x"one_answers";y"。该列表是根据每个元素的创建方式排序的:首先是"AAA",然后是"BBB",我不想按创建顺序排序,而是按父元素中的每个元素排序。

另外,第二个问题是将其定位在X和Y(对于我正在创建的项目)。基本上,对于元素的左侧或上方的每个父元素,它将被拖动到右侧或下方20px。在这个例子中,"CCC"元素有"AAA"作为父母,所以它是向右20px,同时"AAA", "BBB"one_answers";EEE"都在上面。所以"ccc"的位置是(20,60).

我尝试了下面的方法。正常情况下,我甚至可以读懂父母的第一行,但每个孩子里面的孩子都没有按照我想要的方式去读或理解。如果有人能帮助我,我将永远感激。

for value in name_list:
if value["parent"] == "none":
loop = True
loop_list = value["children"]
while loop:
for child_name in loop_list:
child = get_item(child_name)
if len(child["children"]) != 0:
loop_list = child["children"]
print("result") ;(

我猜你想要这样的东西:

my_list = [
{"name": "AAA", "parent": "none", "children": ["BBB", "CCC", "DDD"], "x": 0, "y": 0},
{"name": "BBB", "parent": "AAA", "children": ["EEE"], "x": 20, "y": 20},
{"name": "CCC", "parent": "AAA", "children": ["FFF"], "x": 20, "y": 60},
{"name": "DDD", "parent": "AAA", "children": [], "x": 20, "y": 100},
{"name": "EEE", "parent": "BBB", "children": [], "x": 40, "y": 40},
{"name": "FFF", "parent": "CCC", "children": [], "x": 40, "y": 80},
{"name": "GGG", "parent": "none", "children": ["HHH"], "x": 0, "y": 120},
{"name": "HHH", "parent": "GGG", "children": [], "x": 0, "y": 140},
]
def print_tree(node, indent=0):
print("    " * indent + f"{node['name']} ({node['x']}, {node['y']})")
for child_name in node['children']:
child = next(item for item in my_list if item["name"] == child_name)
print_tree(child, indent+1)
# set initial coordinates for the root nodes
for node in my_list:
if node['parent'] == 'none':
print_tree(node)

输出:

AAA (0, 0)
BBB (20, 20)
EEE (40, 40)
CCC (20, 60)
FFF (40, 80)
DDD (20, 100)
GGG (0, 120)
HHH (0, 140)

最新更新