python - 为什么这个 return 语句会在这个 python 递归函数中抛出一个错误?
问题描述
我正在通过对列表中的所有元素求和来练习使用递归函数。
我做的功能是:
def list_sum_recursive(input_list):
#base case, list is empty
if input_list == []:
print("empty")
return
#recursive case
else:
#grab the first element
head = input_list[0]
del input_list[0]
#return the sum of the head plus the sum of the rest of the list
return head + list_sum_recursive(input_list)
但是,此函数会引发此错误:
类型错误:+ 不支持的操作数类型:“int”和“NoneType”
我确实找到了解决方案,制作了基本案例return 0
而不是return
.
但是现在我很好奇平原return
是做什么的,或者没有做什么来引发错误?为什么在 python 这种非常灵活和宽容的语言中,这样的事情是一个问题?
解决方案
只是想给你一个更 Pythonic 的版本,希望你不要介意。
def list_sum_recursive(input_list):
#base case, list is empty
if not input_list:
return 0
#return the sum of the head plus the sum of the rest of the list
return input_list.pop(0) + list_sum_recursive(input_list)
print(list_sum_recursive([1,2,3]))
推荐阅读
- powershell - 如何在 Powershell 会话中保持更改?
- logging - 使用 Gelf logback appender 在 Logstash 中创建动态索引
- salesforce - Salesforce 中从演示到实际帐户的设置
- python - 无法在虚拟环境中通过 Jupyter Notebook 连接到 Python
- facebook - 链接到 Facebook 个人资料的网站(2021 年 7 月)
- javascript - 形成多步 javascript 和引导程序
- java - 使用 LinkedHashMaps 从 Object 获取和修改值
- javascript - Firebase 身份验证返回未定义的 createUserWithEmailAndPassword
- excel - 在 VBA 中查找特定字符串并选择行的宏
- angular - 使用角度应用程序时在手机浏览器中重复会话