【问题标题】:Python :Iterating list of listPython:迭代列表列表
【发布时间】:2016-11-25 04:38:42
【问题描述】:
['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);

我无法通过上面的方式获得这种输出。是否有可能获得这种输出?

【问题讨论】:

  • 为什么需要queue,这通常用于迭代解决方案与递归解决方案。顺便说一句:不要使用 list 作为变量名 - 它隐藏了 python list 类型。广度优先打印迭代会更简单(队列)。
  • 在进行递归时还需要处理基本情况。这里的基本情况是树是一个空列表
  • 我想,你的同学今天问了同样的问题here
  • @schwobaseggl 不知道..

标签: python list data-structures tree


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 2015-09-25
    • 2019-01-09
    • 2013-04-09
    相关资源
    最近更新 更多