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

其他回答

从文档中:

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

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

你可能经常发现

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

一个替代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的评论

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

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

它变成:

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

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

特纳利条件运营商简单地允许在单一线测试一个条件,取代多线,如果它使代码紧凑。

合成:

假如他是真實的,

1、使用Ternary Operator的简单方法:

# Program to demonstrate conditional operator
a, b = 10, 20
# Copy value of a in min if a < b else copy b
min = a if a < b else b
print(min)  # Output: 10

2、直接使用Tuples、词典和Lambda的方法:

# Python program to demonstrate ternary operator
a, b = 10, 20
# Use tuple for selecting an item
print( (b, a) [a < b] )
# Use Dictionary for selecting an item
print({True: a, False: b} [a < b])
# lambda is more efficient than above two methods
# because in lambda  we are assure that
# only one expression will be evaluated unlike in
# tuple and Dictionary
print((lambda: b, lambda: a)[a < b]()) # in output you should see three 10

3、管道运营商可以写作如下:

# Python program to demonstrate nested ternary operator
a, b = 10, 20
print ("Both a and b are equal" if a == b else "a is greater than b"
        if a > b else "b is greater than a")

上面的方法可以写作如:

# Python program to demonstrate nested ternary operator
a, b = 10, 20
if a != b:
    if a > b:
        print("a is greater than b")
    else:
        print("b is greater than a")
else:
    print("Both a and b are equal")
# Output: b is greater than a