1. 程式人生 > >python 中 ? : 三元表示式 的實現方式

python 中 ? : 三元表示式 的實現方式

剛剛學python的時候,時常糾結於python中沒有C語言中 ? : 的實現,今天終於發現了兩種python的實現方式:

(1) variable = a if exper else b

(2)variable = (exper and [b] or [c])[0]

(2) variable = bool(exper) and b or c 

上面三種用法都可以達到目的,類似C語言中 variable = exper ? b : c;即:如果exper表示式的值為true則variable = b,否則,variable = c

例如:

a,b=1,2
max = (a if a > b else b)
max = (a > b and [a] or [b])[0] #list
max = (a > b and a or b)