python 条件运算符的另一种语法糖实现形式

在 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 指定的那部分,而不会都都执行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值