刚刚学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)