簡體   English   中英

Python 遞歸 function 反轉列表

[英]Python recursive function that reverses a list

我的代碼圖片

我想寫一個遞歸的 function 來反轉列表。 給定輸入:[1,2,3],function 應該返回 [3,2,1]

但是,我收到此錯誤消息。

在此處輸入圖像描述

試試這樣:

def reverse(lst,start,end):
      if start>=end:
         return lst
      else:
        temp=lst[start]
        lst[start]=lst[end]
        lst[end]=temp
        return reverse(lst,start+1,end-1)

l = [1,2,3]
print(reverse(l,0,len(l)-1))

Output:

[3, 2, 1]

不需要任何遞歸編程:

list_in = [1, 2, 3]
list_out = list_in[::-1]

newList.append(temp)沒有返回值,因此返回 None。 newList.append(temp)將 temp 添加到 newList,因此您的代碼可以用作:

def recursiveReverse(dataList):
    if len(dataList) == 1:
        return dataList
    else:
        temp = dataList.pop(0)
        newList = recursiveReverse(dataList)
        newList.append(temp)
        return newList

從我在錯誤消息中看到的情況來看,它拋出的錯誤是您正在嘗試 append 某些內容為無類型,如行中的return yourlist.append(element) 首先嘗試附加到列表,然后返回它。 喜歡

mylist.append(element)
return mylist

在 python 中,列表是可變對象, list.append向現有列表添加一個元素但不返回任何內容。 這就是您收到該錯誤的原因。

暫無
暫無

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

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