在 C 语言中,有条件运算符 a ? b : c
在 Python 中,一般直接用 if else 来实现,也就是:
variable = A if cond else B
今天在阅读 PaddleDetection 源码时,发现一种新的语法糖
variable = cond and A or B
cond 为 True 则 A, 为 False 则 B
此处做一个实验测试一下看看以上二者是否相同
from tqdm import tqdm
import numpy as np
nums = 1000000
def return_data():
cond = np.random.randint(2, size=(nums,), dtype=bool)
num_arr = np.random.uniform(2, 10000, size=(nums, 2))
for i in range(nums):
yield cond[i], num_arr[i][0], num_arr[i][1]
def and_or_func(cond, one, other):
return cond and one or other
def if_else_func(cond, one, other):
return one if cond else other
for idx, data in tqdm(enumerate(return_data()), total=nums):
c, on, ot = data
assert and_or_func(c, on, ot) == if_else_func(c, on, ot)
随机生成数据,最终未报错即可,再看看另一个例子:
import numpy as np
def resA():
print("执行 A 函数")
return "A"
def resB():
print("执行 B 函数")
return "B"
cond = np.random.rand() > 0.5
res_if_else = resA() if cond else resB()
res_and_or = cond and resA() or resB()
assert res_if_else == res_and_or
and / or 与 if / else 相同,都是只执行 cond 指定的那部分,而不会都都执行