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


当前回答

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为几种原因:

其他回答

做事的神秘方式:

"true" if var else "false"

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

"true" and var or "false"

你可能经常发现

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

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

合成:

假如他是真實的,

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

test: or_test ['if' or_test 'else' test] | lambdef

兴趣的一部分是:

or_test ['if' or_test 'else' test]

expression1 if expression2 else expression3

expression3 将被轻松评估(即只有在 boolean 背景下, expression2 是虚假的),并且由于重复的定义,你可以无限地链接它们(也许它可能被认为是坏风格)。

expression1 if expression2 else expression3 if expression4 else expression5 # and so on

人们学习列表的理解和发明表达可能认为这是一个难以学习的教训 - 以下不会工作,因为Python预期另一个第三个表达:

[expression1 if expression2 for element in iterable]
#                          ^-- need an else here

[expression1 for element in iterable if expression2]

expression1 if expression1 else expression2

expression1 or expression2

请注意,一些风格指南可以根据清晰度限制这种使用 - 它包装了很多意义到很少的合成。

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

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