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


当前回答

从文档中:

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

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

其他回答

你可以这样做:

[condition] and [expression_1] or [expression_2];

例子:

print(number%2 and "odd" or "even")


注: 0, 没有, 虚假, 虚假, 和 emptyString 被评为 虚假。

除0以外的任何数据都被评为真实。

如果我们“和”与0(零)的东西,结果将永远是虚假的。

0 and exp

表达式 exp 将不会被评估,因为“和”与 0 将始终被评估为零,并且不需要评估表达式。

1 or exp

exp 表达式将不会被评估,因为“或”与 1 将永远是 1. 所以不会打扰评估 exp 表达式,因为结果将是 1 无论如何(计算机优化方法)。

但是,如果

True and exp1 or exp2

同样在

False and exp1 or exp2

exp1 表达式不会被评估,因为 False 相当于 0 写作,并且与 0 做“和”将是 0 本身,但在 exp1 使用“或”之后,它将评估 exp2 表达式后“或”。


[condition] and ([expression_1] or 1) or [expression_2];

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

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

许多从 C 产生的编程语言通常具有以下条件运营商的合成:

<condition> ? <expression1> : <expression2>

起初,Python的善良独裁者为生命(我指的是Guido van Rossum,当然)拒绝它(作为非Pythonic风格),因为它是相当难以理解的人不使用C语言。

<expression1> if <condition> else <expression2>

因此,首先,它评估了状态. 如果它返回真,表达1将被评估给结果,否则表达2将被评估。

下面是几个例子(条件将从左向右评估):

pressure = 10
print('High' if pressure < 20 else 'Critical')

# Result is 'High'

Ternary 运营商可以分为序列:

pressure = 5
print('Normal' if pressure < 10 else 'High' if pressure < 20 else 'Critical')

# Result is 'Normal'

下一个与前一个相同:

pressure = 5

if pressure < 20:
    if pressure < 10:
        print('Normal')
    else:
        print('High')
else:
    print('Critical')

# Result is 'Normal'

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