无限极分类算法
数据结构:
create table web_class (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"name" varchar(255) NOT NULL, --名称
"bid" integer, --上级ID
)
数据库数据:
{id:1, name:'名称1', bid:0}
{id:2, name:'名称2', bid:0}
{id:3, name:'名称3', bid:1}
{id:4, name:'名称4', bid:1}
{id:5, name:'名称5', bid:3}
{id:6, name:'名称6', bid:5}
需要实现的树形菜单(类似如下):
[{'bid':0,'id':1,'name':'名称1',
'son':[
{'bid':1,'id':3,'name':'名称3',
'son':[
{'bid':3,'id':5,'name':'名称5',
'son':[
{'bid':5,'id':6,'name':'名称6','son':[]}
]
}
]
},
{'bid':1,'id':4,'name':'名称4','son':[]}
]
},
{'bid':0,'id':2,'name':'名称2','son':[]}]
算法来了(有两种方式)
用树实现
def xTree(datas):
lists=[]
tree={}
parent_id=''
for i in datas:
item=i
tree[item['id']]=item
root=None
for i in datas:
obj=i
if not obj['bid']:
root=tree[obj['id']]
lists.append(root)
else:
parent_id=obj['bid']
if 'children' not in tree[parent_id]:
tree[parent_id]['children']=[]
tree[parent_id]['children'].append(tree[obj['id']])
return lists
print(xTree(datas))
和上面一样的思想
def get_tree(data):
lists = []
tree = {}
for item in data:
tree[item['cat_id']] = item
print(tree)
for item in data:
# 找到子根
if not item['parent_id']:
lists.append(tree[item['cat_id']])
else:
parent_id = item['parent_id']
# 如果没有children键 就加进去,并且赋值为空,以便后面加进去儿级数据
if "children" not in tree[parent_id]:
tree[parent_id]["children"] = []
tree[parent_id]['children'].append(tree[item['cat_id']])
return lists
递归实现
lis = []
def get_son1(data, parent_id=0, level=0, is_clear=True):
if is_clear:
lis.clear()
for item in data:
if item['parent_id'] == parent_id:
item['level'] = level
lis.append(item)
get_son1(data, parent_id=item["cat_id"], level=level + 1, is_clear=False)
return lis