Python如何打印树形结构
已知List如下:
list = [ {'id':1, 'title':'t1', 'parent_id':0}, {'id':2, 'title':'t2', 'parent_id':0}, {'id':3, 'title':'t1_1', 'parent_id':1}, {'id':4, 'title':'t1_2', 'parent_id':1}, {'id':5, 'title':'t1_2_1', 'parent_id':4}, {'id':6, 'title':'t2_1', 'parent_id':2}, ]
要求实现如下效果:
t1
t1_1
t1_2
t1_2_1
t2
t2_1
解决方案如下:
#方法1: def printList(parentId, tree, spaceStr = ''): for x in tree: if x['parent_id'] == parentId: print(spaceStr, x['title'], sep = '') printList(x['id'], tree, spaceStr + ' ') printList(0, list)