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


当前回答

正如我已经回答过的那样,是的,在Python中有一个特纳里操作员:

<expression 1> if <condition> else <expression 2>

在许多情况下, < 表达 1> 也被用作 Boolean 评估的 < 条件>. 然后您可以使用短循环评估。

a = 0
b = 1

# Instead of this:
x = a if a else b
# Evaluates as 'a if bool(a) else b'

# You could use short-circuit evaluation:
x = a or b

短循环评估的一个大专业是链接超过两个表达式的可能性:

x = a or b or c or d or e

当与功能工作时,它在细节上更不同:

# Evaluating functions:
def foo(x):
    print('foo executed')
    return x


def bar(y):
    print('bar executed')
    return y


def blubb(z):
    print('blubb executed')
    return z


# Ternary Operator expression 1 equals to False
print(foo(0) if foo(0) else bar(1))
''' foo and bar are executed once
foo executed
bar executed
1
'''

# Ternary Operator expression 1 equals to True
print(foo(2) if foo(2) else bar(3))
''' foo is executed twice!
foo executed
foo executed
2
'''

# Short-circuit evaluation second equals to True
print(foo(0) or bar(1) or blubb(2))
''' blubb is not executed
foo executed
bar executed
1
'''

# Short-circuit evaluation third equals to True
print(foo(0) or bar(0) or blubb(2))
'''
foo executed
bar executed
blubb executed
2
'''

# Short-circuit evaluation all equal to False
print(foo(0) or bar(0) or blubb(0))
''' Result is 0 (from blubb(0)) because no value equals to True
foo executed
bar executed
blubb executed
0
'''

PS:当然,一个短循环评估不是一个电路运营商,但经常在短循环足够的情况下使用电路,它具有更好的可读性,可以连锁。

其他回答

Vinko Vrsalovic的答案是足够好的,只有一件事:

請注意,條件是表達,而不是表達,這意味著您無法在條件表達內使用任命表達或通過或其他表達。

华鲁斯操作员在Python 3.8

在Walrus操作器在Python 3.8中引入后,有些事情发生了变化。

(a := 3) if True else (b := 5)

给 a = 3 和 b 不定义,

(a := 3) if False else (b := 5)

给 a 不定义 和 b = 5 和

c = (a := 3) if False else (b := 5)

给 c = 5, a 不定义, b = 5 。

即使这可能是丑陋的,任务可以在Python 3.8之后的条件表达中进行。

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

从文档中:

条件表达式(有时称为“永久运营商”)具有所有 Python 操作的最低优先事项. 表达式 x 如果 C 其他 y 首先评估条件, C (不是 x); 如果 C 是真实的, x 被评估并返回值; 否则, y 被评估并返回值。

此分類上一篇: 最新版本 2.5.

连接多个运营商的方式:

f = lambda x,y: 'greater' if x > y else 'less' if y > x else 'equal'

array = [(0,0),(0,1),(1,0),(1,1)]

for a in array:
  x, y = a[0], a[1]
  print(f(x,y))

# Output is:
#   equal,
#   less,
#   greater,
#   equal

对于 Python 2.5 或更高版本,有一个具体的合成:

[on_true] if [cond] else [on_false]

在更老的Pythons中,一个特纳运营商没有实施,但可以模拟它。

cond and on_true or on_false

雖然有一個可能的問題,即如果 cond 評估到 True 和 on_true 評估到 False 然後 on_false 返回而不是 on_true. 如果你想要這種行為的方法是 OK,否則使用此方法:

{True: on_true, False: on_false}[cond is True] # is True, not == True

可以包装的:

def q(cond, on_true, on_false)
    return {True: on_true, False: on_false}[cond is True]

以此方式使用:

q(cond, on_true, on_false)

它与所有 Python 版本兼容。