res = []
#递归分类法
def get_con(data,parent_id=0,clas=True):
if clas:
res.clear()
for i in data:
if i["parent_id"] == parent_id:
res.append(i)
get_con(data,parent_id=i["cat_id"],clas=False)
return res
res2 = get_con(data)
print(res2)
#迭代分类法
data=[
{"cat_id":1,"name":"北京","parent_id":0},
{"cat_id":2,"name":"上海","parent_id":0},
{"cat_id":3,"name":"沙河","parent_id":1},
{"cat_id":4,"name":"sb镇","parent_id":3},
{"cat_id":5,"name":"昌平","parent_id":1},
{"cat_id":6,"name":"青浦","parent_id":2},
]
def get_tree(data):
lists = []
tree = {}
for i in data:
tree[i["cat_id"]]=i
#首先给tree 赋值 k为 data内的cat_id,v为data的每一条数据
for dic in data:
data_num = dic["parent_id"]
if not data_num:
lists.append(tree[dic["cat_id"]])
#取出parent_id为零的数据 只有两条 取出添加到lists
else:
if "chiden" not in tree[data_num]:
#判断这个字典里面是不是有这个字段
tree[data_num]["chiden"]=[]
#没有就添加然后给这个字段变成一个列表
tree[data_num]["chiden"].append(tree[dic["cat_id"]])
return lists
ress = get_tree(data)
for i in ress:
print(ress)