热线电话:13121318867

登录
2018-12-10 阅读量: 834
三元运算符是什么?

三元运算符(也称为条件表达式)是基于条件为真或假来评估某些内容的运算符。它在2.5版本中被添加到Python中。
它只是允许在一行中测试条件来替换多行if-else使代码紧凑。
句法 :
[on_true] if [expression] else [on_false]

  1. 使用三元运算符的简单方法:

# 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)

2. 使用元组,字典和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])

# lamda 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]())

3. 三元运算符可以写为嵌套if-else:

# 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")

0.0000
4
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子