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


当前回答

你可能经常发现

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

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

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

连接多个运营商的方式:

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

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

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

它变成:

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

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

你可以把它分成一个<unk>子:

(falseValue, trueValue)[test]

测试需要返回真实或虚假. 它可能更安全地总是执行它如下:

(falseValue, trueValue)[test == True]

或者您可以使用内置的 bool() 来确保 Boolean 值:

(falseValue, trueValue)[bool(<expression>)]