首先我有必要记录下来这段代码,因为我遇到了这个问题, 然后没有解决
后来, 前段说我找到一段代码给我看看, 我并没有在意, 然后她实现了, 她实现了,她真的实现了, 我。。。
为了感谢她,我陪她玩了一中午的五子棋, 并假装输了几把
先说目的:
递归迭代
再看数据:
其实有个前提, 就是aid不能重复
fid是父级id, 指向的aid
如果 aid == fid , 证明fid的那个aid是子集
如果 fid == 0 就证明是顶级
代码:
def aaa(oldArr, fid): newArr = [] for i in oldArr: if i["fid"] == fid: obj = {"aid": i["aid"], "description": i["description"]} child = aaa(oldArr, i["aid"]) if len(child) > 0: obj["child"] = child newArr.append(obj) return newArr if __name__ == '__main__': li = [ {"aid": 5, "fid": 1, "description": "职业价值观4", "vid": 1, "variableName": "标准系数"}, {"aid": 1, "fid": 3, "description": "职业价值观1", "vid": 1}, {"aid": 4, "fid": 3, "description": "职业价值观2", "vid": 2}, {"aid": 7, "fid": 3, "description": "职业价值观3", "vid": 3}, {"aid": 2, "fid": 0, "description": "教育", "vid": 4}, {"aid": 3, "fid": 0, "description": "时间", "vid": 5}, ] res = {"dirname": "", "child_dirs": [], "files": []} print(aaa(li, 0))
需求2, 进行树形tree格式前传参格式调整
需求:
代码:
#!/usr/bin/python # -*- coding:utf-8 -*- import os.path import json from pprint import pprint a = [ '/a/1/1.png', '/b/2/2.png', '/a/1/3.png', '/a/5.png', '/7.png', '/a/3/4.png' ] def walk(parent, r, endchild=True): parent, child = os.path.split(parent) if not child == '': r = walk(parent, r, endchild=False) print '获取到上一级的节点dict,增加当前节点的信息[%s]' % r if endchild: print '这里是叶子节点了,添加文件信息' r['files'].append(child) return r else: try: result = [x for x in r['childs'] if x['name'] == './'+child][0] except: print '这里是中间节点,增加中间节点信息[%s, %s]' % (parent, child) r['childs'].append({ "name": './' + child, "files": [], "childs": [] }) result = [x for x in r['childs'] if x['name'] == './'+child][0] print '返回新增的节点作为下一个递归回退的当前节点[%s]' % result return result else: return r if __name__ == '__main__': r = { "name": '/', "files": [], "childs": [] } for i in a: walk(i, r) print json.dumps(r)
结果:
记得拿for最后一个
{ "childs": [{ "childs": [{ "childs": [], "name": "./1", "files": ["1.png", "3.png"] }, { "childs": [], "name": "./3", "files": ["4.png"] }], "name": "./a", "files": ["5.png"] }, { "childs": [{ "childs": [], "name": "./2", "files": ["2.png"] }], "name": "./b", "files": [] } ], "name": "/", "files": ["7.png"] }