1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| def list_to_tree(data): root = [] node = []
for d in data: d["choice"] = 0 if d.get("parent_id") == 0: root.append(d) else: node.append(d) for p in root: add_node(p, node)
if len(root) == 0: return node
return root
def add_node(p, node): p["children"] = [] for n in node: if n.get("parent_id") == p.get("theme_id"): p["children"].append(n)
for t in p["children"]: if not t.get("children"): t["children"] = [] t["children"].append(add_node(t, node))
if len(p["children"]) == 0: p["choice"] = 1 return if __name__ == '__main__': data_list = [{'parent_id': 10023, 'theme_id': 10024, 'theme_name': '英语三级'}, {'parent_id': 10022, 'theme_id': 10023, 'theme_name': '英语二级'}, {'parent_id': 0, 'theme_id': 10025, 'theme_name': '语文一级'}, {'parent_id': 10025, 'theme_id': 10026, 'theme_name': '语文二级'}, {'parent_id': 0, 'theme_id': 10022, 'theme_name': '英语一级'}] data_tree = list_to_tree(data_list) print(data_tree) ''' 结果如下: [ { "parent_id": 0, "theme_id": 10025, "theme_name": "语文一级", "choice": 0, "children": [ { "parent_id": 10025, "theme_id": 10026, "theme_name": "语文二级", "choice": 1, "children": [] } ] }, { "parent_id": 0, "theme_id": 10022, "theme_name": "英语一级", "choice": 0, "children": [ { "parent_id": 10022, "theme_id": 10023, "theme_name": "英语二级", "choice": 0, "children": [ { "parent_id": 10023, "theme_id": 10024, "theme_name": "英语三级", "choice": 1, "children": [] } ] } ] } ] '''
|