Python中的三元运算符

条件表达式(有时称为“三元运算符”)在所有Python操作中优先级最低。三元运算符根据条件为真或假来计算某些东西。
它只允许在单行中测试条件,取代多行if-else,使代码紧凑。

语法:

[on_true] if [expression] else [on_false] 
expression : conditional_expression | lambda_expr

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

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

输出

10

说明:表达式min用于根据给定条件打印a或b。例如,如果a小于b,则输出是a,如果a不小于b,则输出是b。

使用元组、字典和lambda


# Python program to demonstrate ternary operator
a, b = 10, 20
 
# Use tuple for selecting an item
# (if_test_false,if_test_true)[test]
# if [a<b] is true it return 1, so element with 1 index will print
# else if [a<b] is false it return 0, so element with 0 index will print
print( (b, a) [a < b] )
 
# Use Dictionary for selecting an item
# if [a < b] is true then value of True key will print
# else if [a<b] is false then value of False key will print
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]())

输出

10
10
10

三元运算符可以写成嵌套的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")

上述方法可以写成:

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

输出

 b is greater than a

在三元运算符中使用print函数

示例:在python中使用三元运算符查找2者较大的数

a=5
b=7
 
# [statement_on_True] if [condition] else [statement_on_false]
 
print(a,"is greater") if (a>b) else print(b,"is Greater")

输出

7 is Greater

注意事项:

  • 首先对给定的条件求值(a < b),然后根据条件返回的布尔值返回a或b
  • 操作符中参数的顺序与其他语言(如C/C++)不同。
  • 条件表达式在所有Python操作中具有最低的优先级。

使用for循环

要在for循环中使用三元运算符,可以按照以下步骤操作:

  • 使用for语句循环要计算的数据。
  • 使用三元运算符计算数据中的每个元素。
  • 打印每个元素的三元运算符的结果。

在下例中,要评估的数据存储在称为data的列表中。for语句用于循环遍历列表中的每个元素。三元运算符用于确定每个数字是偶数还是奇数。三元运算符的结果存储在名为result的变量中。print()语句用于打印列表中每个元素的三元运算符的结果。

# Define the data to be evaluated
data = [3, 5, 2, 8, 4]
# Use a for loop to evaluate each element in the data
for num in data:
    # Use the ternary operator to determine if the number is even or odd
    result = 'even' if num % 2 == 0 else 'odd'
    # Optionally, print the result of the ternary operator for each element
    print(f'The number {num} is {result}.')

输出

The number 3 is odd.
The number 5 is odd.
The number 2 is even.
The number 8 is even.
The number 4 is even.

代码定义了一个称为data的整数列表。然后它使用for循环遍历列表中的每个元素。对于每个元素,它使用三元运算符来检查它是偶数还是奇数,并将结果保存到名为result的变量中。然后,代码可选地打印每个元素的三元运算符的结果。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值