条件表达式(有时称为“三元运算符”)在所有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。
# 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
# else if [a
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
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
# 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
示例:在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
注意事项:
要在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的变量中。然后,代码可选地打印每个元素的三元运算符的结果。