美文网首页程序园
一个Java 程序员的python学习之路4-Ternary 操

一个Java 程序员的python学习之路4-Ternary 操

作者: 赵阳_c149 | 来源:发表于2019-10-18 17:34 被阅读0次

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)

参考:Ternary Operators

相关文章

网友评论

    本文标题:一个Java 程序员的python学习之路4-Ternary 操

    本文链接:https://www.haomeiwen.com/subject/dfkwmctx.html