《Python+Cookbook》笔记 递归 中运用的三目运算符

版权声明:本文为博主原创文章,欢迎大家转载交流。 https://blog.csdn.net/object_bitch/article/details/81660232

看书的时候遇到  return head + sum(tail) if tail else head 返回,第一反应是if else 语句   然后就想冒号去哪了

实则这里运用了三目运算符

# 三目运算符 [on_true] if [expression] else [on_false]

print(11 + 100000 if 0 else 0)   


# 说明三目运算符中if前 表达式为一体(起码加号优先级高)
#当判断为假时 返回0 而不是   11+0

items = [1, 10]
def sum(items):
  head, *tail = items
  #return 11 + 100000 if 0 else 0
  return head + sum(tail) if tail else 0
print(sum(items))  # 1

 #而执行逻辑如下 
 #return  1 + sum([10])
 #return  1 + (10 + sum([]) if [] else 0)
 #return  1 
 #也反应了为什么在最后一次递归时 为什么没有因为else的0 而把前面的计算结果覆盖
 #而是返回了前值与 0 相加

《Python+Cookbook》 中一个递归示例:也是这个关于三目运算的问题发起的地方

items = [1, 10, 7, 4, 5, 9]
def sum(items):
  head, *tail = items
  #return 11 + 100000 if 0 else 0
  return head + sum(tail) if tail else head 
print(sum(items))  # 36


# 所以最后一次递归为  return 27 + (9 + sum([]) if [] else 9 )   
# return 27 + 9 
# return 36 

猜你喜欢

转载自blog.csdn.net/object_bitch/article/details/81660232