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

Python三目运算符与递归
本文解析了Python中的三目运算符用法,并通过一个递归函数示例展示了如何利用三目运算符简化代码。文章解释了递归过程中三目运算符的工作原理及其实现细节。

看书的时候遇到  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 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值