标签:分类 pen res _id turn not 父类 print parent
数据格式: data=[ {"cat_id":3,"name":"青浦","parent_id":1}, {"cat_id": 2, "name": "张江", "parent_id": 4}, {"cat_id":4,"name":"浦东","parent_id":1}, {"cat_id":5, "name": "北京", "parent_id": 0}, {"cat_id":6, "name": "昌平", "parent_id": 5}, {"cat_id": 1, "name": "上海", "parent_id": 0}, ] 第一种处理(递归): 将数据如下输出: 上海 -青浦 -浦东 --张江 北京 -昌平 ```` 代码如下: res = [] def get_son(data,level = 0,parent_id = 0 ): for item in data: if item[‘parent_id‘] == parent_id : item[‘level‘] =level res.append(item) get_son(data,level+1,item[‘cat_id‘]) return res 代码的执行过程 ‘‘‘ 1 p=0,l=0 北京 c = 5,找北京的儿子,p =5 l=0+1 昌平 c =6 ,找昌平的儿子 ,p=6 l =1+1 上海 c =1 ,找上海的儿子 ,p=1 l=0+1 青浦 c=3 找青浦的儿子 p=3 l = 1+1 "浦东" cat_id":4 找浦东的儿子,p=4 l=1+1 张江 c = 2 找张江的儿子 p=2 l=l+1+1 ‘‘‘ 第二种树的行式: 需求如下: 讲data 数据变成data1 data1 = [ { "cat_id": 1, "name": "上海", "parent_id": 0, "children":[ {"cat_id":3,"name":"青浦","parent_id":1}, {"cat_id": 4, "name": "浦东", "parent_id": 1,"children": [{"cat_id": 2, "name": "张江", "parent_id": 4},]}, ] }, {"cat_id": 5, "name": "北京", "parent_id": 0,"children":[]}, ] 这样就可以通过循环嵌套的级数显示几级分类。 for item in data1: print("一级分类:",item[‘name‘]) for item1 in item["children"]: print("二级分类:",item1.get(‘name‘)) 代码如下: def get_tree(data): #lists = [{"cat_id":5, "name": "北京", "parent_id": 0,"children":[]},{"cat_id": 1, "name": "上海", "parent_id": 0}] lists= [] tree = {} for i in data: tree[i["cat_id"]] = i # {3:{"cat_id":3,"name":"青浦","parent_id":1},...} for item in data: if item[‘parent_id‘] == 0: # 说明它为根节点 lists.append(tree[item[‘cat_id‘]]) # 插入根节点的字典 else: if "children" not in tree[item["parent_id"]]: # 判断每一个父类字典有没有children的key tree[item[‘parent_id‘]][‘children‘] = [] # 添加children的空值key tree[item[‘parent_id‘]][‘children‘].append(tree[item[‘cat_id‘]]) # 把儿子对象添加进去 return lists
标签:分类 pen res _id turn not 父类 print parent
原文地址:https://www.cnblogs.com/ludingchao/p/12507568.html