[英]Reversing a list using recursion does not give the expected output
I'm looking to reverse a list using recursion in python. 我想在python中使用递归来反转列表。 I succeeded in doing so but the output isn't exactly what I wanted. 我成功地做到了,但是输出并不是我想要的。 trying to figure out where i'm going wrong. 试图找出我要去哪里。
def revlist(ls):
newlist = []
n = len(ls)
if n == 1:
return ls[-1]
else:
return ls[-1],revlist(ls[:-1])
This is my output. 这是我的输出。
revlist([1,2,3,4])
(4, (3, (2, 1)))
What i'm really hoping to get is this: 我真正希望得到的是:
revlist([1,2,3,4])
(4,3,2,1)
You're closeish. 你太近了
def revlist(ls):
newlist = []
n = len(ls)
if n == 1:
return [ls[-1]]
else:
return [ls[-1]] + revlist(ls[:-1])
Or cleaned up: 或清理:
def revlist(ls):
if len(ls) < 1:
return []
else:
return [ls[-1]] + revlist(ls[:-1])
Basically, you need to always return a list
from your function, and append recursive calls appropriately. 基本上,您需要始终从函数中返回一个list
,并适当地追加递归调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.