用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

多个条件表达式也可以使用逻辑运算符(和、或等)进行串联。

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

注意,尽管与三元运算符无关,但上面的例子为λ表达式指定了一个名字。因此,自动检查工具,如Python的编码惯例PEP8可能会产生一个警告。

这是因为PEP8推荐在为函数赋名时使用def。

PEP8的概念如下

  • 兰姆达表达式被用来传递可调用对象作为参数,例如,不命名它们
  • 在lambda表达式中,使用def来定义名称
Copied title and URL