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


当前回答

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

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

其他回答

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

合成:

假如他是真實的,

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

不幸的是,该

(falseValue, trueValue)[test]

解决方案没有短循环行为;因此,无论情况如何,FalseValue和 trueValue都被评估,这可能是低优化或甚至错误(即 trueValue和 falseValue都可能是方法,并且有副作用)。

其中一个解决方案将是

(lambda: falseValue, lambda: trueValue)[test]()

(执行延迟到获胜者知道;)),但它引入可称和不可称的对象之间的不一致性。

因此,故事正在进行 - 选择上述三个解决方案是使用至少Python 2.5(IMHO,不再是一个问题)和不倾向于“真实价值评估到虚假”错误之间的交换。

在 2.5 之前的版本中,有以下技巧:

[expression] and [on_true] or [on_false]

它可以提供错误的结果,当 on_true 具有虚假的 Boolean 值。

雖然它有評估表達的好處留在右邊,這在我看來更清楚。

是否有“C”的“?”:“特纳利运营商的同等值?

作为Python Enhancement Proposal 308的一部分,2006年在Python中添加了一个条件表达的操作员,其形式不同于常见的?:操作员,它看起来如下:

<expression1> if <condition> else <expression2>

相当于:

if <condition>: <expression1> else: <expression2>

下面是一个例子:

result = x if a > b else y

可使用的另一个合成(可与 2.5 之前的版本兼容):

result = (lambda:y, lambda:x)[a > b]()

工人被精心评估。

另一种方式是通过索引一个<unk>(不符合大多数其他语言的条件运营商):

result = (y, x)[a > b]

或明确构建的词典:

result = {True: x, False: y}[a > b]

另一个(不太可靠),但更简单的方法是使用和和或运营商:

result = (a > b) and x or y

但是,如果 x 是虚假的,它就不会工作。

一个可能的工作岗位是创建 x 和 y 列表或列表如下:

result = ((a > b) and [x] or [y])[0]

或:

result = ((a > b) and (x,) or (y,))[0]

如果您正在使用字典,而不是使用一个温和的条件,您可以利用获得(关键,默认),例如:

shell = os.environ.get('SHELL', "/bin/sh")

来源:?:在维基百科的Python

<表达 1> 如果 <条件> 其他 <表达 2>

a = 1
b = 2

1 if a > b else -1 
# Output is -1

1 if a > b else -1 if a < b else 0
# Output is -1