Python 無限級分類樹狀結構生成演算法的實現

2022-10-04 13:12:27 字數 1700 閱讀 4166

後端研發的同學對無限級分類肯定映像深刻,當初花了不少時間吧?

作者在初次接觸樹狀結構生成需求的時候,也是撓頭,後來找到tngafuvfxy了乙個**少且清晰易懂的生成演算法:遞迴。

首先,確保資料庫中儲存的類別資訊如下:

[, ,

, ,, ,

, ,]

字段 parent 記錄的是此條目的父編號,例如電吹風的父編號是 3,即電吹風屬於家用電器,而家用電器的父編號是 1,即家用電器屬於電器類產品。程式設計客棧電吹風條目跟電器條目並無直接的標識進行關聯,但需要用樹狀結構來表明 電器

通過 parent 尋找父編號,並建立關聯關係的操作實際上是迴圈往復的,直到找完所有的結點,這跟遞迴演算法非常契合,很輕鬆便能寫出對應的遞迴**:

def generate_tree(source, parent):

tree =

for item in source:

if item["parent"] == parent:

item["child"] = generate_tree(source, item["id"])

tree.append(item)

return tree

只需要將資料庫中存程式設計客棧儲的資訊傳遞給 generate_tree 函式即可。這段遞迴**在往復迴圈的過程中通過 parent 來尋找子結點,找到子結點後將其新增到樹中。完整**如下:

import json

def generate_tree(source, parent):

tree =

for item in source:

if item["parent"] == parent:

item["child"] = generate_tree(source, item["id"])

tree.append(item)

return tree

if __name__ == '__main__':

permission_source = [

, ,, ,

, ,, ,

] permission_tree = generate_tree(permission_source, 0)

print(json.dumps(permission_tree, ensure_ascii=false))

你試試執行一下,看看結構是否符合預期。

遞迴演算法中有很多重複的計算,這些計算不僅占用額外資源,還會降低函式執行效率,因此需要對遞迴進行優化。這裡選用快取優化法提公升函式執行效率。

基本思路是每次找到結點關係後將此條目的編號新增到乙個列表中快取起來,代表此條目已找到結點關係。當往復迴圈執行函式時再次遇到此條目可以跳過。**改動很簡單,增加乙個快取列表和控制流語句即可:

def generate_tree(source, parent, cache=):

tree =

for item in source:

if item["id"] in cache:

continue

if item["parent"] == parent:

cache.append(item["id"])

item["child"] = generate_tree(source, item["id"], cache)

tree.append(item)

return tree

至此,無限級分類樹狀結構生成演算法完成。你學會了嗎?

無限級分類

相信在實際專案中很多人在做專案的時候都會用到無限級分類,無限級分類說白了就是乙個遞迴,遞迴在我們的專案開發中起到很重要的作用,如 麵包屑導航等。下面我們演示乙個遞迴的案例 area array array id 1,name 安徽 parent 0 array id 2,name 海淀 parent...

無限級分類

無限極分類其實就是乙個遞迴便利 1,查詢所有資料 namespace home controller use think controller class indexcontroller extends controller 2,遞迴便利資料 namespace home model use thi...

無限級分類

將資料如下輸出 上海 青浦 浦東 張江 北京 昌平 data res def get son data,level 0,parent id 0 for item in data 如果當前迴圈的parent id parent id,將level等級新增到列表中 if item parent id p...