使用 Python 的三元運算符(條件運算符)在一行中編寫 if 語句

商業

Python 有一種稱為三元運算符(條件運算符)的寫作風格,它可以在單行中描述一個類似 if 語句的過程。

此處解釋了以下內容以及示例代碼。

  • 三元運算符的基本寫法
  • if ... elif ... else ...用一行來描述這個
  • 結合列表綜合符號和三元運算符
  • 匿名函數(lambda 表達式)和三元運算符的組合

有關正常 if 語句的更多信息,請參閱以下文章。

三元運算符的基本寫法

在 Python 中,三元運算符可以寫成如下

Expression evaluated when the conditional expression is true if conditional expression else Expression evaluated when the conditional expression is false

如果要根據條件切換值,只需按原樣寫入每個值。

Value to return if conditional expression is true if conditional expression else Value to return if conditional expression is false
a = 1
result = 'even' if a % 2 == 0 else 'odd'
print(result)
# odd

a = 2
result = 'even' if a % 2 == 0 else 'odd'
print(result)
# even

如果要根據條件切換處理,請描述每個表達式。

a = 1
result = a * 2 if a % 2 == 0 else a * 3
print(result)
# 3

a = 2
result = a * 2 if a % 2 == 0 else a * 3
print(result)
# 4

不返回值的表達式(返回 None 的表達式)也是可以接受的。根據條件,計算表達式之一併執行該過程。

a = 1
print('even') if a % 2 == 0 else print('odd')
# odd

相當於下面用普通 if 語句編寫的代碼。

a = 1

if a % 2 == 0:
    print('even')
else:
    print('odd')
# odd

也可以使用邏輯運算符(and、or 等)連接多個條件表達式。

a = -2
result = 'negative and even' if a < 0 and a % 2 == 0 else 'positive or odd'
print(result)
# negative and even

a = -1
result = 'negative and even' if a < 0 and a % 2 == 0 else 'positive or odd'
print(result)
# positive or odd

if ... elif ... else ...一行描述

if ... elif ... else ...沒有特殊的方法可以將其寫在一行上。但是,可以通過在三元運算符的條件表達式為假時計算的表達式中使用另一個三元運算符來實現。嵌套三元運算符的圖像。

但是,最好不要廣泛使用它,因為它會降低可讀性。

a = 2
result = 'negative' if a < 0 else 'positive' if a > 0 else 'zero'
print(result)
# positive

a = 0
result = 'negative' if a < 0 else 'positive' if a > 0 else 'zero'
print(result)
# zero

a = -2
result = 'negative' if a < 0 else 'positive' if a > 0 else 'zero'
print(result)
# negative

下面的條件表達式可以用以下兩種方式解釋,但被視為前一種(1)。

A if condition 1 else B if condition 2 else C
1. A if condition 1 else ( B if condition 2 else C )
2. ( A if condition 1 else B ) if condition 2 else C 

一個具體的例子如下。第一個表達式被認為是第二個。

a = -2
result = 'negative' if a < 0 else 'positive' if a > 0 else 'zero'
print(result)
# negative

result = 'negative' if a < 0 else ('positive' if a > 0 else 'zero')
print(result)
# negative

result = ('negative' if a < 0 else 'positive') if a > 0 else 'zero'
print(result)
# zero

結合列表綜合符號和三元運算符

三元運算符的一個有用用途是在以列表理解表示法處理列表時。

通過結合三元運算符和列表理解符號,可以根據條件替換列表的元素或執行一些其他處理。

l = ['even' if i % 2 == 0 else i for i in range(10)]
print(l)
# ['even', 1, 'even', 3, 'even', 5, 'even', 7, 'even', 9]
l = [i * 10 if i % 2 == 0 else i for i in range(10)]
print(l)
# [0, 1, 20, 3, 40, 5, 60, 7, 80, 9]

有關列表理解表示法的更多信息,請參閱以下文章。

匿名函數(lambda 表達式)和三元運算符的組合

即使在匿名函數(lambda 表達式)中也可以簡潔地描述的三元運算符很有用。

get_odd_even = lambda x: 'even' if x % 2 == 0 else 'odd'

print(get_odd_even(1))
# odd

print(get_odd_even(2))
# even

請注意,儘管與三元運算符無關,但上面的示例為 lambda 表達式分配了一個名稱。因此,Python 的編碼約定 PEP8 等自動檢查工具可能會產生警告。

這是因為 PEP8 建議在為函數分配名稱時使用 def。

PEP8的概念如下

  • Lambda 表達式用於將可調用對像作為參數傳遞,例如,無需命名它們
  • 在 lambda 表達式中,使用 def 按名稱定義
Copied title and URL