在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),但合成对我来说更清楚。
其他回答
一个替代Python的条件表达
"yes" if boolean else "no"
是如下:
{True: "yes", False: "no"}[boolean]
有下列好延伸:
{True: "yes", False: "no", None: "maybe"}[boolean_or_none]
最短的替代品
("no", "yes")[boolean]
因为它是以子类(bool, int)为作用。
注意,但是:替代
yes() if boolean else no()
不是
(no(), yes())[boolean] # bad: BOTH no() and yes() are called
但
(no, yes)[boolean]()
這工作很好,只要沒有,是的,應該用相同的數字呼叫。
yes("ok") if boolean else no() # (1)
或在
yes("ok") if boolean else no("sorry") # (2)
因此,相似的替代品既不存在(一)又几乎不可行(二)。(在罕见的情况下,根据背景,某种类似的
msg = ("sorry", "ok")[boolean]
(no, yes)[boolean](msg)
可以有意义( )
谢谢Radek Rojík的评论
有多种方式,最简单的是在“印刷”方法中使用状态。
你可以使用
print("Twenty" if number == 20 else "Not twenty")
相当于:
if number == 20:
print("Twenty")
else:
print("Not twenty")
因此,可以打印超过两份声明,例如:
if number == 20:
print("Twenty")
elif number < 20:
print("Lesser")
elif 30 > number > 20:
print("Between")
else:
print("Greater")
可以写作如:
print("Twenty" if number == 20 else "Lesser" if number < 20 else "Between" if 30 > number > 20 else "Greater")
做事的神秘方式:
"true" if var else "false"
但是,总是有不同的方式来做一个温和的状态:
"true" and var or "false"
<表达 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
如果否则版本可以写作如下:
sample_set="train" if "Train" in full_path else ("test" if "Test" in full_path else "validation")