在Python中是否有特纳利条件操作器?
当前回答
a if condition else b
记住这个金字塔,如果你有记住问题:
condition
if else
a b
其他回答
是的,Python有一个特纳运营商,这里是合成和一个示例代码来展示相同的:)
#[On true] if [expression] else[On false]
# if the expression evaluates to true then it will pass On true otherwise On false
a = input("Enter the First Number ")
b = input("Enter the Second Number ")
print("A is Bigger") if a>b else print("B is Bigger")
如果否则版本可以写作如下:
sample_set="train" if "Train" in full_path else ("test" if "Test" in full_path else "validation")
在 2.5 之前的版本中,有以下技巧:
[expression] and [on_true] or [on_false]
它可以提供错误的结果,当 on_true 具有虚假的 Boolean 值。
雖然它有評估表達的好處留在右邊,這在我看來更清楚。
是否有“C”的“?”:“特纳利运营商的同等值?
你可以这样做:
[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操作员. 我想补充提到一个场景,操作员经常使用,但有一个更好的字符。
假设我们希望使用选项_值与默认值,如果它没有设置:
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中,年龄从出生日期开始
- 使用pip安装SciPy
- PHP中的双not(!!)操作符
- 在Python中,我应该如何测试变量是否为None, True或False
- 如何在Python中从毫秒创建datetime ?
- 如何解窝(爆炸)在一个熊猫数据帧列,成多行
- 如何使用pip安装opencv ?
- 在pip冻结命令的输出中“pkg-resources==0.0.0”是什么
- 格式y轴为百分比
- 熊猫连接问题:列重叠但没有指定后缀
- 为什么空字典在Python中是一个危险的默认值?
- 在Python中,冒号等于(:=)是什么意思?
- Python "SyntaxError:文件中的非ascii字符'\xe2' "
- 如何从psycopg2游标获得列名列表?
- Python中dict对象的联合