在Python中是否有特纳利条件操作器?
当前回答
如果否则版本可以写作如下:
sample_set="train" if "Train" in full_path else ("test" if "Test" in full_path else "validation")
其他回答
许多从 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'
是的,它有,但它与C类似的编程语言不同(这是条件? value_if_true : value_if_false
在 Python 中,它如下: value_if_true 如果另一个条件值_if_false
例如: even_or_odd = “even” 如果 x % 2 == 0 其他 “odd”
模拟 Python Ternary 操作器。
例如
a, b, x, y = 1, 2, 'a greather than b', 'b greater than a'
result = (lambda:y, lambda:x)[a > b]()
出口:
'b greater than a'
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为几种原因:
你可能经常发现
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
推荐文章
- Pandas和NumPy+SciPy在Python中的区别是什么?
- 将列表转换为集合会改变元素的顺序
- 静态隐式运算符
- 如何在matplotlib更新一个情节
- TypeError: ` NoneType `对象在Python中不可迭代
- 如何在Vim注释掉一个Python代码块
- python标准库中的装饰符(特别是@deprecated)
- 如何从外部访问本地Django web服务器
- 删除字符串的最后3个字符
- 在python中执行no-op的标准方法是什么?
- 如何从生成器构建numpy数组?
- 逗号运算符是做什么的?
- 什么时候我应该(不)想要在我的代码中使用熊猫apply() ?
- 数据类vs类型。NamedTuple主要用例
- 如何从macOS完全卸载蟒蛇