Ternary 操作在java中非常常见:
int source = 1;
int target = source ==1 ? 1 : 2;
在python中,也有类似的实现,主要有以下几种形式:
- 从2.4开始,Ternary操作通常是作为条件表达式出现的。
is_nice = True
state = "nice" if is_nice else "not nice"
- 还有一种更加晦涩因此并不常用的方法,该方法涉及tuples:
nice = True
personality = ("mean", "nice")[nice]
print("The cat is ", personality)
# Output: The cat is nice
- 还有一种ShortHand形式的Ternary:
output = None
msg = output or "No data returned"
print(msg)
网友评论