如何解决反转列表的递归函数返回“无”
我正在尝试使用递归函数反转 python 中的列表。下面给出的 python 程序采用三个参数列表 lst
,一个起始索引 start
,列表应该从这里反转和结束索引 end
。但该函数返回 None
,我不明白为什么?
def reverse(lst,start,end):
if start>=end:
return lst
else:
temp=lst[start]
lst[start]=lst[end]
lst[end]=temp
reverse(lst,start+1,end-1)
解决方法
你也需要从 else 部分返回。如您所知,递归函数的 if 部分通常是基本条件,最有可能是最后一个函数调用中的运行。所以你也需要返回之前函数调用的答案。
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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。