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


当前回答

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

[expression] and [on_true] or [on_false]

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

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

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

其他回答

一个提示比一个答案更多(我不需要重复显而易见的百度),但有时我用它作为一个单线缩短在这样的结构:

if conditionX:
    print('yes')
else:
    print('nah')

它变成:

print('yes') if conditionX else print('nah')

有些(很多)可能在它上被称为无神论(甚至,Ruby-ish :),但我个人觉得它更自然 - 也就是说,你会如何正常表达它,加上在大块代码中更有视觉吸引力。

是的,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")

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

(falseValue, trueValue)[test]

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

(falseValue, trueValue)[test == True]

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

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

一个替代Python的条件表达

"yes" if boolean else "no"

是如下:

{True: "yes", False: "no"}[boolean]

有下列好延伸:

{True: "yes", False: "no", None: "maybe"}[boolean_or_none]

最短的替代品

("no", "yes")[boolean]

因为它是以子类(bool, int)为作用。

注意,但是:替代

yes() if boolean else no()

不是

(no(), yes())[boolean]  # bad: BOTH no() and yes() are called

(no, yes)[boolean]()

這工作很好,只要沒有,是的,應該用相同的數字呼叫。

yes("ok") if boolean else no()  # (1)

或在

yes("ok") if boolean else no("sorry")  # (2)

因此,相似的替代品既不存在(一)又几乎不可行(二)。(在罕见的情况下,根据背景,某种类似的

msg = ("sorry", "ok")[boolean]
(no, yes)[boolean](msg)

可以有意义( )

谢谢Radek Rojík的评论

有多种方式,最简单的是在“印刷”方法中使用状态。

你可以使用

print("Twenty" if number == 20 else "Not twenty")

相当于:

if number == 20:
    print("Twenty")
else:
    print("Not twenty")

因此,可以打印超过两份声明,例如:

if number == 20:
    print("Twenty")
elif number < 20:
    print("Lesser")
elif 30 > number > 20:
    print("Between")
else:
    print("Greater")

可以写作如:

print("Twenty" if number == 20 else "Lesser" if number < 20 else "Between" if 30 > number > 20 else "Greater")