在Python中是否有特纳利条件操作器?
当前回答
许多从 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'
其他回答
在 2.5 之前的版本中,有以下技巧:
[expression] and [on_true] or [on_false]
它可以提供错误的结果,当 on_true 具有虚假的 Boolean 值。
雖然它有評估表達的好處留在右邊,這在我看來更清楚。
是否有“C”的“?”:“特纳利运营商的同等值?
特纳利条件运营商简单地允许在单一线测试一个条件,取代多线,如果它使代码紧凑。
合成:
假如他是真實的,
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操作员. 我想补充提到一个场景,操作员经常使用,但有一个更好的字符。
假设我们希望使用选项_值与默认值,如果它没有设置:
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的条件表达
"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的评论
你可能经常发现
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
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录