(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
例如:
[python] view plaincopy
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)