有一个数据表idfidtitle1-1python2-1ruby3-1php4-1lisp51flask61django71webpy82rails93zend106dblog这是一个栏目表,title是栏目名称,id是栏目id,fid是栏目的父id.构建一个多级栏目分类通过python查询处理,会得到下面的一个元祖,t=((1,-1,'python'),(2,-1,'ruby'),(3,-1,'php'),(4,-1,'lisp'),(5,1,'flask'),(6,1,'django'),(7,1,'webpy'),(8,2,'rails'),(9,3,'zend'),(10,6,'dblog'))希望通过python处理,转换成下面的list字典树l=[{'id':1,'fid':-1,'title':'python','son':[{'id':5,'fid':1,'title':'flask',},{'id':6,'fid':1,'title':'django','son':[{'id':10,'fid':6,'title':'dblog',},]},{'id':7,'fid':1,'title':'webpy',},]},{'id':2,'fid':-1,'title':'ruby','son':[{'id':8,'fid':2,'title':'rails',},]},{'id':3,'fid':-1,'title':'php','son':[{'id':9,'fid':3,'title':'zend',},]},{'id':4,'fid':-1,'title':'lisp',}]也就是类似网站的目录,父栏目包含子栏目.自己写了好几个,感觉效率不够好,求大神更pythonic的方法在stackoverflow有人回答大概如下:frompprintimportpprintl=[]entries={}forid,fid,titleint:entries[id]=entry={'id':id,'fid':fid,'title':title}iffid==-1:l.append(entry)else:parent=entries[fid]parent.setdefault('son',[]).append(entry)pprint(l)
ibeautiful
相关分类