Python:迭代列表列表

时间:2016-11-25 04:38:42

标签: python list data-structures tree

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

这是我的清单,我需要以特定的方式迭代它。以下输出应为: -

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);

我无法通过上述方式得到这种输出。是否可以获得这种输出?

1 个答案:

答案 0 :(得分:1)

我通过在你的问题中只假设给定的模式来粗略地做到这一点。

var vc1 = UIViewController()
var vc2 = vc1
var vc3 = vc2
weak var vc4 = vc3

我从中获得的输出。

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)