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


当前回答

在 2.5 之前的版本中,有以下技巧:

[expression] and [on_true] or [on_false]

它可以提供错误的结果,当 on_true 具有虚假的 Boolean 值。

雖然它有評估表達的好處留在右邊,這在我看來更清楚。

是否有“C”的“?”:“特纳利运营商的同等值?

其他回答

不幸的是,该

(falseValue, trueValue)[test]

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

其中一个解决方案将是

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

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

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

不同编程语言的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

许多从 C 产生的编程语言通常具有以下条件运营商的合成:

<condition> ? <expression1> : <expression2>

起初,Python的善良独裁者为生命(我指的是Guido van Rossum,当然)拒绝它(作为非Pythonic风格),因为它是相当难以理解的人不使用C语言。

<expression1> if <condition> else <expression2>

因此,首先,它评估了状态. 如果它返回真,表达1将被评估给结果,否则表达2将被评估。

下面是几个例子(条件将从左向右评估):

pressure = 10
print('High' if pressure < 20 else 'Critical')

# Result is 'High'

Ternary 运营商可以分为序列:

pressure = 5
print('Normal' if pressure < 10 else 'High' if pressure < 20 else 'Critical')

# Result is 'Normal'

下一个与前一个相同:

pressure = 5

if pressure < 20:
    if pressure < 10:
        print('Normal')
    else:
        print('High')
else:
    print('Critical')

# Result is 'Normal'

模拟 Python Ternary 操作器。

例如

a, b, x, y = 1, 2, 'a greather than b', 'b greater than a'
result = (lambda:y, lambda:x)[a > b]()

出口:

'b greater than a'

是的,Python有一个特纳运营商,这里是合成和一个示例代码来展示相同的:)

#[On true] if [expression] else[On false]
# if the expression evaluates to true then it will pass On true otherwise On false

a = input("Enter the First Number ")
b = input("Enter the Second Number ")

print("A is Bigger") if a>b else print("B is Bigger")