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


当前回答

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

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

其他回答

不幸的是,该

(falseValue, trueValue)[test]

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

其中一个解决方案将是

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

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

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

在Python中,Ternary Operator的合成是:

假如他是真實的,

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

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

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

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

你可能经常发现

cond and on_true or on_false

但这会导致一个问题,当 on_true == 0

>>> x = 0
>>> print x == 0 and 0 or 1
1
>>> x = 1
>>> print x == 0 and 0 or 1
1

在哪里你会期望这个结果为一个正常的特纳利运营商:

>>> x = 0
>>> print 0 if x == 0 else 1
0
>>> x = 1
>>> print 0 if x == 0 else 1
1

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

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

它变成:

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

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