2013-04-28 97 views
0

我在找出一个函数的实现时遇到了一点问题。递归显示嵌套列表

基本上,我有一个嵌套列表,我需要像这样显示出来:

Root 
    -RItem1 
     --Item1 
     --RRItem2 
     --Item1 
     --Item2 
    -RItem2 
     --RRItem1 
      -Item1 
      -Item2 
     --Item2 

注意,我会在运行系统中获取数据。一个物品可能有一个物品,有一个物品有物品等。

所以基本上,一个程序如何呢?我知道递归函数是要走的路,但我遇到了麻烦。具体来说,我很难考虑我的物品的坐标。

这是一个执行问题,所以语言并不重要。

+0

可不可以给这些名单是如何嵌套的一个例子即 '[ “RItem1”,[ “项目1,[” RRItem2" ,[ “项目1”],[ “项目2”]]]]' – HennyH 2013-04-28 13:42:27

+0

@ HennyH不幸的是,数据使用链接列表以相当复杂的方式排列。 – Secret 2013-04-28 13:48:17

回答

3

递归函数是一个好方法。你必须通过'水平'作为参数。类似的东西(假的Java/Java脚本):

function display(item, level) { 
    printlnAtLevel(level,item.name) 
    if item.hasChildren() { 
     foreach(child : item.children) { 
      display(child,level+1) 
     } 
    } 
} 
display(root,0) 
+0

谢谢@ l4mpi,我编辑了我的帖子。 – Thierry 2013-04-28 12:17:41

+0

我决定不接受这个答案,因为我觉得y坐标是一个问题。经过很多思考,我意识到这是一个问题,我仍然无法做到。我怎么能决定y?我可以将函数作为全局函数保存在外部,但我怎样才能“递归地”执行它。哦,非常感谢:3 – Secret 2013-04-28 13:25:25

+0

在上面的代码中,如果我有1. {a,b} 2.“2”将其级别设为“1”,而不是b。如果我的解释很难理解,请回复,我会尽量详细说明。谢谢! – Secret 2013-04-28 13:34:51

1

我寄与(X,Y)另外一个答案:

function display(item, x, y) { 
    print(x,y,item.name) 
    if item.hasChildren() { 
    yTemp = y + 1 
    foreach(child : item.children) { 
     display(child,x+1,yTemp++) 
    } 
    } 
} 
display(root,0,0) 
1
def nodePrint(val,depth): 
    print(" "*depth + "-"*depth,val) 

def recPrint(l,depth=0): 
    #node has no children A) it contains 1 or 0 elements B) if not A then'child' is string 
    if len(l) <= 1 or isinstance(l[1],str): 
     for value in l: 
     nodePrint(value,depth) 
    else: 
     #node had both head and child in form [ head, [ child1, ... ] ] 
     head, children = l[0],l[1:] 
     nodePrint(head,depth) 
     for child in children: 
     recPrint(child,depth+1) 

使用下列内容:

t = ["Root", 
    [ 
     "Ritem1", 
      [ 
       "Item1", 
       [ 
       ] 
      ], 
      [ 
       "RRItem2", 
       [ 
       "Item1", 
       "Item2" 
       ] 
      ] 
    ], 
    ["Ritem1", 
     [ 
     "RRItem1", 
     [ 
      "Item1", 
      "Item2" 
      ] 
     ], 
     ["Item2"] 
    ] 
    ] 

recPrint(t,depth=0) 

生产(与您要求相同)

>>> 
Root 
- Ritem1 
    -- Item1 
    -- RRItem2 
    --- Item1 
    --- Item2 
- Ritem1 
    -- RRItem1 
    --- Item1 
    --- Item2 
    -- Item2