详解Python中三元运算符的使用

 更新时间:2023年09月05日 08:56:23   作者:python收藏家  
条件表达式(有时称为“三元运算符”)在所有Python操作中优先级最低,三元运算符根据条件为真或假来计算某些东西,下面就跟随小编一起来看看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的变量中。然后,代码可选地打印每个元素的三元运算符的结果。

到此这篇关于详解Python中三元运算符的使用的文章就介绍到这了,更多相关Python三元运算符内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论