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


当前回答

做事的神秘方式:

"true" if var else "false"

但是,总是有不同的方式来做一个温和的状态:

"true" and var or "false"

其他回答

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

a if condition else b

这使得短循环,因为当状态是真实的,只有A被评估,而B根本不被评估,但当状态是虚假的,只有B被评估,而A根本不被评估。

例如:

>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'

請注意,條件是表達,而不是表達,這意味著你無法在條件表達中使用表達,如通過,或與 = (或「增加」的表達,如 +=) 的表達:

>>> pass if False else pass
  File "<stdin>", line 1
    pass if False else pass
         ^
SyntaxError: invalid syntax

>>> # Python parses this as `x = (1 if False else y) = 2`
>>> # The `(1 if False else x)` part is actually valid, but
>>> # it can't be on the left-hand side of `=`.
>>> x = 1 if False else y = 2
  File "<stdin>", line 1
SyntaxError: cannot assign to conditional expression

>>> # If we parenthesize it instead...
>>> (x = 1) if False else (y = 2)
  File "<stdin>", line 1
    (x = 1) if False else (y = 2)
       ^
SyntaxError: invalid syntax

(在 3.8 及以上, := “walrus” 操作员允许简单地将值定义为表达式,这与此同步,但请不要这样写代码,很快就会变得非常难以理解。

# Invalid syntax: we didn't specify what the value should be if the 
# condition isn't met. It doesn't matter if we can verify that
# ahead of time.
a if True

但是,您可以使用条件表达式来分配变量如下:

x = a if True else b

例如,返回值:

# Of course we should just use the standard library `max`;
# this is just for demonstration purposes.
def my_max(a, b):
    return a if a > b else b


请记住,它是由一些Pythonists为几种原因:

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

你可以使用

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")

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

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

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