在Python中打印列表的非递归方法

时间:2009-07-22 06:42:57

标签: python recursion

有没有办法以非递归方式执行以下操作:

my_list = [
    "level 1-1",
    "level 1-2",
    "level 1-3",
        [
            "level 2-1",
            "level 2-2",
            "level 2-3",
            [
                "level 3-1",
                "level 3-2"
            ]
        ],
    "level 1-4",
    "level 1-5"
    ]


def print_list(the_list, indent_level=0):
    for item in the_list:
        if isinstance(item, list):
            print_list(item, indent_level + 1)
        else:
            print "\t" * indent_level, item


print_list(my_list)

5 个答案:

答案 0 :(得分:4)

stack = [(my_list, -1)]
while stack:
    item, level = stack.pop()

    if isinstance(item, list):
        for i in reversed(item):
            stack.append((i, level+1))
    else:
        print "\t" * level, item

答案 1 :(得分:2)

def print_list(the_list, indent_level=0):
    stack = [iter(the_list)]
    while stack:
        try:
            item = stack[-1].next()
        except StopIteration:
            stack.pop()
            indent_level -= 1
            continue
        if isinstance(item, list):
            indent_level += 1
            stack.append(iter(item))
        else:
            print "\t" * indent_level, item

答案 2 :(得分:2)

以下是MartinLöwis版本的变体,它使用for/else而不是手动捕获StopIterationlen(stack),而不是跟踪缩进级别。

def print_list(the_list):
    stack = [iter(the_list)]
    while stack:
        for item in stack[-1]:
            if isinstance(item, (list, tuple)):
                stack.append(iter(item))
                break
            else:
                print '\t' * (len(stack)-1), item
        else:
            stack.pop()

答案 3 :(得分:0)

请注意,这取决于不包含元组的输入。

l1 = my_list
done = False

# Repeatedly turn the list elements into tuples of the form
# (indent, item) until there are no more lists.
while not done:
    done = True
    l2 = []
    for item in l1:
        if isinstance(item,tuple):
            indent = item[0]
            item = item[1]
        else:
            indent = 0
        if isinstance(item,list):
            l2.extend( zip( (indent + 1,) * len(item), item) )
            done = False
        else:
            l2.append((indent,item))
    l1 = l2

for indent, item in l1:
    print "\t" * indent, item

答案 4 :(得分:0)

每个人都提供了

的解决方案
  • 生产就绪
  • 使用堆栈,因此与递归相同的问题
  • 或多次通过列表

这是解决方案横向解决方案:)

  • 生产准备但很有趣
  • 没有堆叠或类似的东西,没有列表

-

def my_print(the_list):
    level = -1
    out = []
    levelUp="levelup"
    levelDown="leveldown"

    s =  repr(the_list).replace("', '","\n").replace(
        "', ['", "\n%s\n"%levelUp).replace("['", "\n%s\n"%levelUp).replace(
        "']", "\n%s\n"%levelDown).replace("], '", "\n%s\n"%levelDown)

    for line in s.splitlines():
        if not line: continue
        if line == levelUp:
            level+=1
        elif line == levelDown:
            level-=1
        else:
            print "\t"*level,line

my_print(my_list)

它假定您的列表文本没有一些特殊的子串。