在Python中是否有特纳利条件操作器?
当前回答
你可能经常发现
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
其他回答
连接多个运营商的方式:
f = lambda x,y: 'greater' if x > y else 'less' if y > x else 'equal'
array = [(0,0),(0,1),(1,0),(1,1)]
for a in array:
x, y = a[0], a[1]
print(f(x,y))
# Output is:
# equal,
# less,
# greater,
# equal
在Python中,Ternary Operator的合成是:
假如他是真實的,
使用这个合成,这里是我们如何使用Python的Ternary操作器重写上面的代码:
game_type = 'home'
shirt = 'white' if game_type == 'home' else 'green'
请注意,表达式可能是任何类型的表达式,包括函数呼叫,返回值,评估为真实或虚假。
不同编程语言的Ternary Operator
在这里,我只是试图在编程语言中显示一些重要的区别。
Ternary Operator 在 JavaScript 中
var a = true ? 1 : 0;
# 1
var b = false ? 1 : 0;
# 0
土木运营商在卢比
a = true ? 1 : 0
# 1
b = false ? 1 : 0
# 0
Ternary 运营商在 Scala
val a = true ? 1 | 0
# 1
val b = false ? 1 | 0
# 0
R 编程中的 Ternary 操作员
a <- if (TRUE) 1 else 0
# 1
b <- if (FALSE) 1 else 0
# 0
在Python中使用Ternary Operator
a = 1 if True else 0
# 1
b = 1 if False else 0
# 0
特纳利条件运营商简单地允许在单一线测试一个条件,取代多线,如果它使代码紧凑。
合成:
假如他是真實的,
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
做事的神秘方式:
"true" if var else "false"
但是,总是有不同的方式来做一个温和的状态:
"true" and var or "false"
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象