在Python中是否有特纳利条件操作器?
当前回答
我发现默认的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),但合成对我来说更清楚。
其他回答
做事的神秘方式:
"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
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为几种原因:
其他答案是正确的谈论Python操作员. 我想补充提到一个场景,操作员经常使用,但有一个更好的字符。
假设我们希望使用选项_值与默认值,如果它没有设置:
run_algorithm(option_value if option_value is not None else 10)
或者,如果选项_值从未设置为虚假值(0,“”,等),
run_algorithm(option_value if option_value else 10)
但是,在这种情况下,一个越来越好的解决方案只是写作。
run_algorithm(option_value or 10)
正如我已经回答过的那样,是的,在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:当然,一个短循环评估不是一个电路运营商,但经常在短循环足够的情况下使用电路,它具有更好的可读性,可以连锁。
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象