python 遞迴樹狀結構 和 排序

vx_guanchaoguo0發表於2024-03-25

排序

 def recursive_sort(self, categories):
        categories.sort(key=lambda x: x['sort'])
        for category in categories:
            if category['children']:
                category['children'] = self.recursive_sort(category['children'])

        return categories

樹狀

    def list_to_tree(self, data, parent=None):
        tree = []
        for item in data:
            tmp = {
                "name": item.name,
                "uuid": item.uuid,
                "category_type": item.category_type,
                "parent_category_id": item.parent_category_id,
                "add_datetime": item.add_datetime,
                "sort": item.sort,
                "children": [],
            }
            if tmp['parent_category_id'] == parent:
                children = self.list_to_tree(data, tmp['uuid'])
                if len(children) > 0:
                    tmp['children'] = children
                tree.append(tmp)

        return tree

相關文章