对python 树状嵌套结构的实现思路详解


Posted in Python onAugust 09, 2019

原始数据

原始数据大致是这样子的:

每条数据中的四个数据分别是 当前节点名称,节点描述(指代一些需要的节点属性),源节点(即最顶层节点),父节点(当前节点上一层节点)。

datas = [
 ["root", "根节点", "root", None],
 ["node1", "一级节点1", "root", "root"],
 ["node2", "一级节点2", "root", "root"],
 ["node11", "二级节点11", "root", "node1"],
 ["node12", "二级节点12", "root", "node1"],
 ["node21", "二级节点21", "root", "node2"],
 ["node22", "二级节点22", "root", "node2"],
]

节点类

抽象封装出一个节点类:

class Node(object):
 def __init__(self, name: str, desc, parent: str, children: list):
 """
 初始化
 :param name:
 :param desc:
 :param parent:
 :param children:
 """
 self.name = name
 self.desc = desc
 self.parent = parent
 self.children = children

 def get_nodes(self):
 """
 获取该节点下的全部结构字典
 """
 d = dict()
 d['name'] = self.name
 d['desc'] = self.desc
 d['parent'] = self.parent
 children = self.get_children()
 if children:
  d['children'] = [child.get_nodes() for child in children]
 return d

 def get_children(self):
 """
 获取该节点下的全部节点对象
 """
 return [n for n in nodes if n.parent == self.name]

 def __repr__(self):
 return self.name

将原始数据转换为节点对象

nodes = list()
for data in datas:
 node = Node(data[0], data[1], data[-1], [])
 nodes.append(node)

为各个节点建立联系

for node in nodes:
 children_names = [data[0] for data in datas if data[-1] == node.name]
 children = [node for node in nodes if node.name in children_names]
 node.children.extend(children)

测试

root = nodes[0]
print(root)

tree = root.get_nodes()
print(json.dumps(tree, indent=4))

运行结果:

对python 树状嵌套结构的实现思路详解

原始数据也可以是字典的形式:

### fork_tool.py
import json


class Node(object):
 def __init__(self, **kwargs):
 """
 初始化
 :param nodes: 树的全部节点对象
 :param kwargs: 当前节点参数
 """

 self.forked_id = kwargs.get("forked_id")
 self.max_drawdown = kwargs.get("max_drawdown")
 self.annualized_returns = kwargs.get("annualized_returns")
 self.create_time = kwargs.get("create_time")
 self.desc = kwargs.get("desc")
 self.origin = kwargs.get("origin")
 self.parent = kwargs.get("parent")
 self.children = kwargs.get("children", [])

 def get_nodes(self, nodes):
 """
 获取该节点下的全部结构字典,即建立树状联系
 """
 d = dict()
 d['forked_id'] = self.forked_id
 d['max_drawdown'] = self.max_drawdown
 d['annualized_returns'] = self.annualized_returns
 d['create_time'] = self.create_time
 d['desc'] = self.desc
 d['origin'] = self.origin
 d['parent'] = self.parent
 children = self.get_children(nodes)
 if children:
  d['children'] = [child.get_nodes(nodes) for child in children]
 return d

 def get_children(self, nodes):
 """
 获取该节点下的全部节点对象
 """
 return [n for n in nodes if n.parent == self.forked_id]

 # def __repr__(self):
 # return str(self.desc)


def process_datas(datas):
 """
 处理原始数据
 :param datas:
 :return:
 """
 # forked_infos.append({"forked_id": str(forked_strategy.get("_id")),
 # "max_drawdown": max_drawdown,
 # "annualized_returns": annualized_returns,
 # "create_time": create_time, # 分支创建时间
 # "desc": desc,
 # "origin": origin,
 # "parent": parent,
 # "children": [],
 # })

 nodes = []
 # 构建节点列表集
 for data in datas:
 node = Node(**data)
 nodes.append(node)

 # 为各个节点对象建立类 nosql 结构的联系
 for node in nodes:
 children_ids = [data["forked_id"] for data in datas if data["parent"] == node.forked_id]
 children = [node for node in nodes if node.forked_id in children_ids]
 node.children.extend(children)

 return nodes


test_datas = [
 {'annualized_returns': 0.01,
 'children': [],
 'create_time': 1562038393,
 'desc': 'root',
 'forked_id': '5d1ad079e86117f3883f361e',
 'max_drawdown': 0.01,
 'origin': None,
 'parent': None},

 {'annualized_returns': 0.314,
 'children': [],
 'create_time': 1562060612,
 'desc': 'level1',
 'forked_id': '5d1b2744b264566d3f3f3632',
 'max_drawdown': 0.2,
 'origin': '5d1ad079e86117f3883f361e',
 'parent': '5d1ad079e86117f3883f361e'},

 {'annualized_returns': 0.12,
 'children': [],
 'create_time': 1562060613,
 'desc': 'level11',
 'forked_id': '5d1b2745e86117f3883f3632',
 'max_drawdown': None,
 'origin': '5d1ad079e86117f3883f361e',
 'parent': '5d1b2744b264566d3f3f3632'},

 {'annualized_returns': 0.09,
 'children': [],
 'create_time': 1562060614,
 'desc': 'level12',
 'forked_id': '5d1b2746b264566d3f3f3633',
 'max_drawdown': None,
 'origin': '5d1ad079e86117f3883f361e',
 'parent': '5d1b2744b264566d3f3f3632'},

 {'annualized_returns': None,
 'children': [],
 'create_time': 1562060614,
 'desc': 'level2',
 'forked_id': '5d1b2746e86117f3883f3633',
 'max_drawdown': None,
 'origin': '5d1ad079e86117f3883f361e',
 'parent': '5d1ad079e86117f3883f361e'},

 {'annualized_returns': None,
 'children': [],
 'create_time': 1562060627,
 'desc': 'level21',
 'forked_id': '5d1b2753b264566d3f3f3635',
 'max_drawdown': None,
 'origin': '5d1ad079e86117f3883f361e',
 'parent': '5d1b2746e86117f3883f3633'},

 {'annualized_returns': None,
 'children': [],
 'create_time': 1562060628,
 'desc': 'level211',
 'forked_id': '5d1b2754b264566d3f3f3637',
 'max_drawdown': None,
 'origin': '5d1ad079e86117f3883f361e',
 'parent': '5d1b2753b264566d3f3f3635'},

 {'annualized_returns': None,
 'children': [],
 'create_time': 1562060640,
 'desc': 'level212',
 'forked_id': '5d1b2760e86117f3883f3634',
 'max_drawdown': None,
 'origin': '5d1ad079e86117f3883f361e',
 'parent': '5d1b2753b264566d3f3f3635'},
]


if __name__ == "__main__":
 nodes = process_datas(test_datas)
 info = nodes[0].get_nodes(nodes)
 print(json.dumps(info, indent=4))

以上这篇对python 树状嵌套结构的实现思路详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python实现竖排打印传单手机号码易撕条
Mar 16 Python
深入理解NumPy简明教程---数组1
Dec 17 Python
Python实现PS图像调整黑白效果示例
Jan 25 Python
padas 生成excel 增加sheet表的实例
Dec 11 Python
python小程序实现刷票功能详解
Jul 17 Python
对Django 中request.get和request.post的区别详解
Aug 12 Python
PYTHON实现SIGN签名的过程解析
Oct 28 Python
python pptx复制指定页的ppt教程
Feb 14 Python
pycharm 更改创建文件默认路径的操作
Feb 15 Python
python上selenium的弹框操作实现
Jul 13 Python
编写python代码实现简单抽奖器
Oct 20 Python
学点简单的Django之第一个Django程序的实现
Feb 24 Python
Python  Django 母版和继承解析
Aug 09 #Python
python实现爬虫抓取小说功能示例【抓取金庸小说】
Aug 09 #Python
python实现BP神经网络回归预测模型
Aug 09 #Python
Django ORM 聚合查询和分组查询实现详解
Aug 09 #Python
解决Django后台ManyToManyField显示成Object的问题
Aug 09 #Python
详解Python中的正斜杠与反斜杠
Aug 09 #Python
图文详解Django使用Pycharm连接MySQL数据库
Aug 09 #Python
You might like
PHP网站开发中常用的8个小技巧
2015/02/13 PHP
PHP图像识别技术原理与实现
2016/10/27 PHP
php-fpm重启导致的程序执行中断问题详解
2019/04/29 PHP
用JavaScript和注册表脚本实现右键收藏Web页选中文本
2007/01/28 Javascript
javascript 异常处理使用总结
2009/06/21 Javascript
删除javascript中注释语句的正则表达式
2014/06/11 Javascript
JS模式之单例模式基本用法
2015/06/30 Javascript
jQuery时间插件jquery.clock.js用法实例(5个示例)
2016/01/14 Javascript
JS在onclientclick里如何控制onclick的执行
2016/05/30 Javascript
Bootstrap Table服务器分页与在线编辑应用总结
2016/08/08 Javascript
NodeJS远程代码执行
2016/08/28 NodeJs
利用bootstrapValidator验证UEditor
2016/09/14 Javascript
百度地图API之百度地图退拽标记点获取经纬度的实现代码
2017/01/12 Javascript
判断横屏竖屏(三种)
2017/02/13 Javascript
Angular中ng-bind和ng-model的区别实例详解
2017/04/10 Javascript
Angular4开发解决跨域问题详解
2017/08/28 Javascript
微信小程序之多文件下载的简单封装示例
2018/01/29 Javascript
浅谈Vue网络请求之interceptors实际应用
2018/02/28 Javascript
深入浅出理解JavaScript闭包的功能与用法
2018/08/01 Javascript
详解javascript replace高级用法
2019/02/17 Javascript
python连接mysql数据库示例(做增删改操作)
2013/12/31 Python
Python常用模块用法分析
2014/09/08 Python
python实现根据月份和日期得到星座的方法
2015/03/27 Python
Python操作csv文件实例详解
2017/07/31 Python
Python cv2 图像自适应灰度直方图均衡化处理方法
2018/12/07 Python
python 通过类中一个方法获取另一个方法变量的实例
2019/01/22 Python
python3 小数位的四舍五入(用两种方法解决round 遇5不进)
2019/04/11 Python
200行python代码实现2048游戏
2019/07/17 Python
Python图像处理库PIL的ImageFilter模块使用介绍
2020/02/26 Python
HTML5页面直接调用百度地图API获取当前位置直接导航目的地的实现代码
2018/03/02 HTML / CSS
IRO美国官网:法国服装品牌
2018/03/06 全球购物
全球领先的中国制造商品在线批发平台:DHgate
2020/01/28 全球购物
信息管理专业学生自荐信格式
2013/09/22 职场文书
中医药大学毕业生自荐信
2013/11/08 职场文书
2014年社区党建工作汇报材料
2014/11/02 职场文书
python b站视频下载的五种版本
2021/05/27 Python