2016-11-25 122 views
0
['P', ['Q', ['R', ['S', 'T'], ['U', 'V']]]] 

这是我的列表,我需要以特定的方式遍历它。对于下面的输出应该是: -Python:列表的迭代列表

P -> Q 
Q -> R 
R -> S U 
S -> T 
U -> V 

我尝试以下的事情: -

def traverse_mystructure(tree): 
    queue = [tree] 

    for list in tree: 
     print list 
     traverse_mystructure(list); 

我不能够得到这样的输出与above.Is能够获得这种的输出?

+0

为什么你需要'队列',这通常用于迭代解决方案与递归。 BTW:不要使用'list'作为变量名 - 它隐藏python的'list'类型。广度优先打印将更加简单迭代(队列)。 – AChampion

+0

您还需要在递归时处理基本情况。这里的基本情况是当树是一个空列表 –

+0

我假设,你的类队友问同样的问题[这里](http://stackoverflow.com/questions/40791675/using-nltk-tree?noredirect=1#comment68807105_40791675)今天。 – schwobaseggl

回答

1

我已经完成了这个粗略的假设只是在你的问题给定的模式。

inputList = ['P', ['Q', ['R', ['S', 'T'], ['U', 'V']]]] 

print inputList 

def printSomeMore(newList): 
    output = "" 
    for sublist in newList: 
     if (len(sublist) == 1): 
      output = sublist + " ->" 
     else: 
      output = output + " " + sublist[0] 
    return output 

def printMyList(myList): 
    for each in myList: 
     if str(myList[0]) == str(each): 
      if (len(myList) == 2): 
       print each, "->", myList[-1][0] 
      if (len(myList) > 2): 
       value = printSomeMore(myList) 
       print value 
     if str(type(each)) == "<type 'list'>": 
      printMyList(each) 

printMyList(inputList) 

我从中得到的输出。

['P', ['Q', ['R', ['S', 'T'], ['U', 'V']]]] 
P -> Q 
Q -> R 
R -> S U 
S -> T 
U -> V 
+0

非常感谢! –

+0

@ user3168473如果它回答您的问题,您是否可以将此标记为接受的答案。 –