我是一个Python新手
我有一个python方法,它递归地返回列表(previous是string的字典,s只是包含在previous字典中的一个字符串)
def path(previous, s):
"Return a list of states that lead to state s, according to the previous dict."
return [] if (s is None) else path(previous, previous[s]) + [s]
我相信这个应该会得到同样的结果
def path(previous, s):
"Return a list of states that lead to state s, according to the previous dict."
if s is None:
return []
else:
path(previous, previous[s]) + [s]
我原以为这两种方法在功能上完全相同,只是第一种更为一致。但是,当我运行第二个方法时
我收到以下错误:
"TypeError: unsupported operand type(s) for +: 'NoneType' and 'list'"
我做错什么了
在第二个方法的else分支中缺少
return
语句:第一种方法使用三元运算符,其返回值(两个中的一个)由
return
语句返回,因此,第二种方法在两个分支中都需要一个return
语句相关问题 更多 >
编程相关推荐