Python:使用递归反向打印列表

时间:2014-10-02 06:34:34

标签: python recursion

我试图弄清楚如何使用递归以相反的顺序打印出列表。 这就是我颠倒列表的方式:

def reverse_list(xs):
    if xs == []:
         return xs
    else:
        new_list = (print_reverse (xs[1:])) + [xs[0]]
        return new_list

这就是我按顺序打印列表的方式:

def print_in_order(l, i = 0):
    if i < len(l):
        print (l[i])
        print_in_order(l, i + 1)

我尝试从函数中的新列表中打印出来,如下所示:

def print_reverse(xs):
    if xs == []:
        return xs
    else:
        new_list = (print_reverse (xs[1:])) + [xs[0]]
    for number in new_list: 
        print (number)

但它引发了一个错误。你如何结合这两个过程?

4 个答案:

答案 0 :(得分:1)

这是最简单的方法之一,它以这种方式使用切片:

>>> example = [1, 2, 3, 4, 5]
>>> example[::-1]
[5, 4, 3, 2, 1]

..如果你想打印它们,就这样做:

>>> for number in example:
...     print(number)
...     
1
2
3
4
5

编辑:

>>> example = [1, 2, 3, 4, 5]

>>> def recursive(list, counter=0):
...     if len(list) > counter:
...         print(list[counter])
...         recursive(list, counter+1)
...     return
... 

>>> recursive(example[::-1])
5
4
3
2
1

答案 1 :(得分:1)

你只需要交换两行:

def print_in_reverse(lst, i=0):
    if i < len(lst):
        print_in_reverse(lst, i + 1)  # Do the recursive call before you
        print (lst[i])              # print instead of after

答案 2 :(得分:0)

如果您只想按相反顺序打印并且不想更改原始列表,则可以像这样修改print_in_order()

#second parameter is length of list
def print_in_reversed(l, i): 
    if i > 0:
        print (l[i-1])
        print_in_order(l, i - 1)

你将用这个例子来称呼它

example = [1,2,3,4,5]    
print_in_order(example, len(example))

答案 3 :(得分:0)

类似的东西(print_in_order改编):

# print l in reverse order, starting from i
# note, that we're allowed not to specify i
def print_in_reverse(l, i = None):
    # if i is not specified    
    if (i is None):
        i = len(l) - 1 

    # we're printing in reverse: 
    # we have to check for beginning of the string instead of ending
    # that's why check for 0 
    if (i >= 0):
        print (l[i])
        print_in_reverse(l, i - 1) # reverse direction: i - 1 instead of i + 1