在Python中是否有特纳利条件操作器?
当前回答
如果否则版本可以写作如下:
sample_set="train" if "Train" in full_path else ("test" if "Test" in full_path else "validation")
其他回答
有多种方式,最简单的是在“印刷”方法中使用状态。
你可以使用
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")
特纳利条件运营商简单地允许在单一线测试一个条件,取代多线,如果它使代码紧凑。
合成:
假如他是真實的,
1、使用Ternary Operator的简单方法:
# Program to demonstrate conditional operator
a, b = 10, 20
# Copy value of a in min if a < b else copy b
min = a if a < b else b
print(min) # Output: 10
2、直接使用Tuples、词典和Lambda的方法:
# Python program to demonstrate ternary operator
a, b = 10, 20
# Use tuple for selecting an item
print( (b, a) [a < b] )
# Use Dictionary for selecting an item
print({True: a, False: b} [a < b])
# lambda is more efficient than above two methods
# because in lambda we are assure that
# only one expression will be evaluated unlike in
# tuple and Dictionary
print((lambda: b, lambda: a)[a < b]()) # in output you should see three 10
3、管道运营商可以写作如下:
# Python program to demonstrate nested ternary operator
a, b = 10, 20
print ("Both a and b are equal" if a == b else "a is greater than b"
if a > b else "b is greater than a")
上面的方法可以写作如:
# Python program to demonstrate nested ternary operator
a, b = 10, 20
if a != b:
if a > b:
print("a is greater than b")
else:
print("b is greater than a")
else:
print("Both a and b are equal")
# Output: b is greater than a
一个替代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的评论
在Python中,Ternary Operator的合成是:
假如他是真實的,
使用这个合成,这里是我们如何使用Python的Ternary操作器重写上面的代码:
game_type = 'home'
shirt = 'white' if game_type == 'home' else 'green'
请注意,表达式可能是任何类型的表达式,包括函数呼叫,返回值,评估为真实或虚假。
一个提示比一个答案更多(我不需要重复显而易见的百度),但有时我用它作为一个单线缩短在这样的结构:
if conditionX:
print('yes')
else:
print('nah')
它变成:
print('yes') if conditionX else print('nah')
有些(很多)可能在它上被称为无神论(甚至,Ruby-ish :),但我个人觉得它更自然 - 也就是说,你会如何正常表达它,加上在大块代码中更有视觉吸引力。