假设数据结构是这样的:有多条数据,每条数据都有属性parent(指向它的所属上级id),自身的唯一标识id。classdataparentid当我拿出其中一条数据的时候,用一个方法计算出所有下级数据。就好比中国行政区数据一样,当我拿到广东省的时候,下面的市级,县级都要得到,如果县级下面还有分级也要一并拿到。我写了一些代码,都太丑陋了,似乎是要用递归,求教一下有没有什么好的思路?
2 回答
慕丝7291255
TA贡献1859条经验 获得超6个赞
这个问题可以转换成N叉树的遍历,将某个节点的所有子节点计算出来。defreturn_all_children(self):"""返回所有的子项:return:"""root=selfifnotroot:return[]que=[]#保存节点的队列res=[]#保存结果的列表que.append(root)#whilelen(que):#判断队列不为空length=len(que)sub=[]#保存每层的节点的值foriinrange(length):current=que.pop(0)#出队列的当前节点print(current)sub.append(current)forchildincurrent.return_children:#所有子结点入队列que.append(child)res.append(sub)#把每层的节点的值加入结果列表returnres
胡子哥哥
TA贡献1825条经验 获得超6个赞
储存空间够大的话可以建立一个字典假如你的数据是个list名字叫CN(中国所有省市县...)parent_d={}foriteminCN:parent=item['parent']ifparentinparent_d:parent_d[parent].append(item['id'])else:parent_d[parent]=[item['id']]之后遍历一下defget_all_children(city_id,parent_d):ifcity_idnotinparent_dornotcity_id:return[]result=[]temp_parent=[city_id]whiletemp:cur_id=temp_parent.pop(-1)result+=parent_d[cur_id]temp_parent=parent_d[cur_id]+temp_parentreturnresult
添加回答
举报
0/150
提交
取消
