Skip to content

Instantly share code, notes, and snippets.

@stoensin
Created February 11, 2020 10:16
Show Gist options
  • Save stoensin/b86aa06c9bdd61fb3c1ef20459b1752d to your computer and use it in GitHub Desktop.
Save stoensin/b86aa06c9bdd61fb3c1ef20459b1752d to your computer and use it in GitHub Desktop.
python 无限级分类 1、寻找到根节点,放入到列表A中。 2、寻找共同的父节点,并放入到字典B。 3、循环遍历根节点A列表,在共同父节点字典B中取出对应的子节点列表C。 4、依次递归遍历子节点列表C,直到没有子节点列表为止。
class Tree(object):
def __init__(self, data):
self.data = data
self.root_node = []
self.common_node = {}
self.tree = []
def get_root_nodes(self) -> list:
"""
遍历data查找根节点
:return:根节点列表
"""
# self.root_node = list(filter(lambda x: x["father_id"] is None, data))
for node in self.data:
if node["father_id"] is None:
self.root_node.append(node)
return self.root_node
def get_common_nodes(self) -> dict:
"""
遍历data寻找共同的父节点
:return: 共同的父节点字典
"""
for node in self.data:
father_id = node.get("father_id")
if father_id:
if father_id not in self.common_node:
self.common_node[father_id] = []
self.common_node[father_id].append(node)
return self.common_node
def get_children(self, father_id: int, child_node: list):
"""
查找子节点
:param father_id:父级ID
:param child_node: 父级孩子节点
:return:
"""
child_list = self.common_node.get(father_id, [])
for item in child_list:
base = dict(name=item["name"], id=item["id"], child=list())
self.get_children(item["id"], base["child"])
child_node.append(base)
def build_tree(self, ) -> list:
"""
生成目录树
:return:
"""
self.get_root_nodes()
self.get_common_nodes()
for root in self.root_node:
base = dict(name=root["name"], id=root["id"], child=list())
self.get_children(base["id"], base["child"])
self.tree.append(base)
return self.tree
data = [
{"id": 1, "father_id": None, "name": "01"},
{"id": 2, "father_id": 1, "name": "0101"},
{"id": 3, "father_id": 1, "name": "0102"},
{"id": 4, "father_id": 1, "name": "0103"},
{"id": 5, "father_id": 2, "name": "010101"},
{"id": 6, "father_id": 2, "name": "010102"},
{"id": 7, "father_id": 2, "name": "010103"},
{"id": 8, "father_id": 3, "name": "010201"},
{"id": 9, "father_id": 4, "name": "010301"},
{"id": 10, "father_id": 9, "name": "01030101"},
{"id": 11, "father_id": 9, "name": "01030102"},
]
new_tree = exTree(data=data)
thetree= new_tree.build_tree()
# print(thetree)
# [{'name': '01', 'id': 1, 'child': [{'name': '0101', 'id': 2, 'child': [{'name': '010101', 'id': 5, 'child': []}, {'name': '010102', 'id': 6, 'child': []}, {'name': '010103', 'id': 7, 'child': []}]}, {'name': '0102', 'id': 3, 'child': [{'name': '010201', 'id': 8, 'child': []}]}, {'name': '0103', 'id': 4, 'child': [{'name': '010301', 'id': 9, 'child': [{'name': '01030101', 'id': 10, 'child': []}, {'name': '01030102', 'id': 11, 'child': []}]}]}]}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment