在Python中是否有特纳利条件操作器?
当前回答
特纳利条件运营商简单地允许在单一线测试一个条件,取代多线,如果它使代码紧凑。
合成:
假如他是真實的,
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中,Ternary Operator的合成是:
假如他是真實的,
使用这个合成,这里是我们如何使用Python的Ternary操作器重写上面的代码:
game_type = 'home'
shirt = 'white' if game_type == 'home' else 'green'
请注意,表达式可能是任何类型的表达式,包括函数呼叫,返回值,评估为真实或虚假。
你可以把它分成一个<unk>子:
(falseValue, trueValue)[test]
测试需要返回真实或虚假. 它可能更安全地总是执行它如下:
(falseValue, trueValue)[test == True]
或者您可以使用内置的 bool() 来确保 Boolean 值:
(falseValue, trueValue)[bool(<expression>)]
在 2.5 之前的版本中,有以下技巧:
[expression] and [on_true] or [on_false]
它可以提供错误的结果,当 on_true 具有虚假的 Boolean 值。
雖然它有評估表達的好處留在右邊,這在我看來更清楚。
是否有“C”的“?”:“特纳利运营商的同等值?
模拟 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'
Vinko Vrsalovic的答案是足够好的,只有一件事:
請注意,條件是表達,而不是表達,這意味著您無法在條件表達內使用任命表達或通過或其他表達。
华鲁斯操作员在Python 3.8
在Walrus操作器在Python 3.8中引入后,有些事情发生了变化。
(a := 3) if True else (b := 5)
给 a = 3 和 b 不定义,
(a := 3) if False else (b := 5)
给 a 不定义 和 b = 5 和
c = (a := 3) if False else (b := 5)
给 c = 5, a 不定义, b = 5 。
即使这可能是丑陋的,任务可以在Python 3.8之后的条件表达中进行。
推荐文章
- Pandas和NumPy+SciPy在Python中的区别是什么?
- 将列表转换为集合会改变元素的顺序
- 静态隐式运算符
- 如何在matplotlib更新一个情节
- TypeError: ` NoneType `对象在Python中不可迭代
- 如何在Vim注释掉一个Python代码块
- python标准库中的装饰符(特别是@deprecated)
- 如何从外部访问本地Django web服务器
- 删除字符串的最后3个字符
- 在python中执行no-op的标准方法是什么?
- 如何从生成器构建numpy数组?
- 逗号运算符是做什么的?
- 什么时候我应该(不)想要在我的代码中使用熊猫apply() ?
- 数据类vs类型。NamedTuple主要用例
- 如何从macOS完全卸载蟒蛇