2017年9月19日

python 的“三元运算符”(?:)

在 Java 中,你可以这样写:

String text = 2 > 3 ? "yes" : "no"  // text = "no"

这是 C 语言里就有的三元运算符,可以简化 if 语句。Python 中不支持这个运算符。

In [23]: print 2 < 1 ? 'yes' : 'no'
  File "<ipython-input-23-87c99040aff7>", line 1
    print 2 < 1 ? 'yes' : 'no'
                ^
SyntaxError: invalid syntax

果真不支持?其实 Python 中只是换了个形式,本质没有变。用单行的 if/else 语句,实现了同样的效果。

In [24]: print 'yes' if 2 < 1 else 'no'
no

In [25]:

“以书为舟,遨游尘世”,
最好的免费 kindle 电子书分享站:

You may also like...

发表回复

您的电子邮箱地址不会被公开。


*