zoukankan      html  css  js  c++  java
  • python 利用列表的浅拷贝(不用递归)实现递归效果, 生成层级菜单建树数据

    import time
    
    def build_tree_c(data):
        """建树:找儿子算法
        1万层节点耗时(秒):7.0288989543914795
        """
        for index, i in enumerate(data):
            for j in data:
                if i["id"]==j["parentId"]:
                    if "children" not in data[index].keys():
                        data[index]["children"] = []
                    data[index]["children"].append(j)
    
        res = [i for i in data if i["parentId"]==0]
        return res
    
    
    def build_tree_p(data):
    	"""建树:找爸爸算法
    	1万层节点耗时(秒):0.005019187927246094
    	"""
    	# 建立一个 id 对 index 的字典
    	res = []
    	c_dict ={}
    	for index, i in enumerate(data):
    		c_dict[i["id"]] = index
    
    	# 用本节点的 parentId 通过字典找到父节点的index
    	for i in data:
    		if i['parentId'] == 0:
    			res.append(i)
    		else:
    			papa = data[c_dict[i["parentId"]]]
    			if "children" not in papa.keys():
    				papa["children"] = []
    			papa["children"].append(i)
    
    	# res = [i for i in data if i["parentId"]==0]
    	return res
    
    
    # 创建一个1万个节点: [{'id': 0, 'parentId': 1}, {'id': 1, 'parentId': 2}, {'id': 2, 'parentId': 3}, ...{'id': 9999, 'parentId': 10000}]
    data = [{"id": i+1,"parentId": i} for i in range(10000)]
    
    # 将这1万个节点建树:
    t1 = time.time()
    res = build_tree_p(data)
    # res = build_tree_c(data)
    t2 = time.time()
    st = t2-t1
    
    print("Start time:	%s
    Stop time:	%s
    Elapsed time:	%s" % (t1, t2, st))
    

      

  • 相关阅读:
    简单读取winfrom资源文件
    string.Format对C#字符串格式化
    如何在SQL中使用循环结构
    Linq to SQL 多条件动态组合查询(实战篇)
    提问的艺术
    XtraGrid 单元格加边框颜色
    凭证控件制作
    C# double 四舍五入
    自定义光标样式
    触发窗体事件(例如按Esc关闭窗体)
  • 原文地址:https://www.cnblogs.com/mzfly/p/13260280.html
Copyright © 2011-2022 走看看