[英]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.