簡體   English   中英

使用遞歸反轉列表不會提供預期的輸出

[英]Reversing a list using recursion does not give the expected output

我想在python中使用遞歸來反轉列表。 我成功地做到了,但是輸出並不是我想要的。 試圖找出我要去哪里。

def revlist(ls):
    newlist = []
    n = len(ls)
    if n == 1:
        return ls[-1]
    else:
        return ls[-1],revlist(ls[:-1])

這是我的輸出。

revlist([1,2,3,4])
(4, (3, (2, 1)))

我真正希望得到的是:

revlist([1,2,3,4])
(4,3,2,1)

你太近了

def revlist(ls):
    newlist = []
    n = len(ls)
    if n == 1:
        return [ls[-1]]
    else:
        return [ls[-1]] + revlist(ls[:-1])

或清理:

def revlist(ls):
    if len(ls) < 1:
        return []
    else:
        return [ls[-1]] + revlist(ls[:-1])

基本上,您需要始終從函數中返回一個list ,並適當地追加遞歸調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM