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


当前回答

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

合成:

假如他是真實的,

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

其他回答

是的,它有,但它与C类似的编程语言不同(这是条件? value_if_true : value_if_false

在 Python 中,它如下: value_if_true 如果另一个条件值_if_false

例如: even_or_odd = “even” 如果 x % 2 == 0 其他 “odd”

<表达 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

作为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

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

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

我发现默认的Python合成val = a if cond other b cumbersome,所以有时我这样做:

iif = lambda (cond, a, b): a if cond else b
# So I can then use it like:
val = iif(cond, a, b)

当然,它有一个缺点,总是评估双方(a和b),但合成对我来说更清楚。