1. 程式人生 > >《Python+Cookbook》筆記 遞迴 中運用的三目運算子

《Python+Cookbook》筆記 遞迴 中運用的三目運算子

看書的時候遇到  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