gpt4 book ai didi

python - 在python循环中填写所需格式的列表

转载 作者:行者123 更新时间:2023-12-01 08:58:02 25 4
gpt4 key购买 nike

我正在尝试在循环中创建列表结构:

[children:[{text: "Title 1", id: '1', expanded: true,children: [{text: "title2", leaf: true ,},{text: "title3", leaf: true}]},{text: "Title4", id: '4', expanded: true, children: [{text: "title5", leaf: true,} ]}]]

源数据如下所示:

mylist =[{'id': '1', 'name': 'Title1', 'id_parent': '0'}, {'id': '2', 'name': 'title2', 'id_parent': '1'}, {'id': '3', 'name': 'title3', 'id_parent': '1'}, {'id': '4', 'name': 'Title4', 'id_parent': '0'}, {'id': '5', 'name': 'title5', 'id_parent': '4'}]

使用递归,我遍历数据并获取 parent 和 child 的记录:

def get_parent(id_parent):
c = []
for x in mylist:
if not x["id"] == id_parent and x["id_parent"] == id_parent:
if x["id_parent"] == id_parent:
x['expanded'] = True
else:
x['leaf'] = True
c.append(x)
return(c)
def get_tree(t):
lst = []
main_data = []
for x in get_parent(t):
all_stor = {}
all_stor["text"] = x['name']
all_stor["id"] = x['id']
if x.get('expanded'):
all_stor["expanded"] = x['expanded']
else:
all_stor["leaf"] = x['leaf']

main_data.append(all_stor)
lst.append([main_data, get_tree(x["id"])])
return lst
main = get_tree("0")
print(main)

如何在循环中填充 main_data 列表以获得必要的结构?

最佳答案

您的预期输出应该是根级别的子级列表:

def get_tree(l, parent='0'):
children = []
for d in l:
if d['id_parent'] == parent:
details = {'text': d['name'], 'id': d['id']}
grand_children = get_tree(l, d['id'])
if grand_children:
details.update({'expanded': True, 'children': grand_children})
else:
details['leaf'] = True
children.append(details)
return children

这样,通过您的示例输入,get_tree(mylist) 将返回:

[{'text': 'Title1', 'id': '1', 'expanded': True, 'children': [{'text': 'title2', 'id': '2 ', 'leaf': True}, {'text': 'title3', 'id': '3', 'leaf': True}]}, {'text': 'Title4', 'id': '4 ', 'expanded': True, 'children': [{'text': 'title5', 'id': '5', 'leaf': True}]}

关于python - 在python循环中填写所需格式的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52666267/

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