在Python中是否有特纳利条件操作器?


当前回答

在Python中,Ternary Operator的合成是:

假如他是真實的,

使用这个合成,这里是我们如何使用Python的Ternary操作器重写上面的代码:

game_type = 'home'
shirt = 'white' if game_type == 'home' else 'green'

请注意,表达式可能是任何类型的表达式,包括函数呼叫,返回值,评估为真实或虚假。

其他回答

如果否则版本可以写作如下:

sample_set="train" if "Train" in full_path else ("test" if "Test" in full_path else "validation")

在Python中,Ternary Operator的合成是:

假如他是真實的,

使用这个合成,这里是我们如何使用Python的Ternary操作器重写上面的代码:

game_type = 'home'
shirt = 'white' if game_type == 'home' else 'green'

请注意,表达式可能是任何类型的表达式,包括函数呼叫,返回值,评估为真实或虚假。

不幸的是,该

(falseValue, trueValue)[test]

解决方案没有短循环行为;因此,无论情况如何,FalseValue和 trueValue都被评估,这可能是低优化或甚至错误(即 trueValue和 falseValue都可能是方法,并且有副作用)。

其中一个解决方案将是

(lambda: falseValue, lambda: trueValue)[test]()

(执行延迟到获胜者知道;)),但它引入可称和不可称的对象之间的不一致性。

因此,故事正在进行 - 选择上述三个解决方案是使用至少Python 2.5(IMHO,不再是一个问题)和不倾向于“真实价值评估到虚假”错误之间的交换。

你可以把它分成一个<unk>子:

(falseValue, trueValue)[test]

测试需要返回真实或虚假. 它可能更安全地总是执行它如下:

(falseValue, trueValue)[test == True]

或者您可以使用内置的 bool() 来确保 Boolean 值:

(falseValue, trueValue)[bool(<expression>)]

不同编程语言的Ternary Operator

在这里,我只是试图在编程语言中显示一些重要的区别。

Ternary Operator 在 JavaScript 中

var a = true ? 1 : 0;
# 1
var b = false ? 1 : 0;
# 0

土木运营商在卢比

a = true ? 1 : 0
# 1
b = false ? 1 : 0
# 0

Ternary 运营商在 Scala

val a = true ? 1 | 0
# 1
val b = false ? 1 | 0
# 0

R 编程中的 Ternary 操作员

a <- if (TRUE) 1 else 0
# 1
b <- if (FALSE) 1 else 0
# 0

在Python中使用Ternary Operator

a = 1 if True else 0
# 1
b = 1 if False else 0
# 0