You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python是否有C++中(var = value, var)这类表达式的等价写法?

Python是否支持C++式的逗号表达式赋值判断写法?

在C++(及C)中,你可以通过逗号表达式实现「赋值后立即用新值判断」的写法,示例代码如下:

uint8_t one = 0;

if ((one = randomUint8t(), one) == 255){
 printf("One has the max uint8_t value");
}

这段代码借助逗号表达式的特性,先执行one = randomUint8t()完成赋值,再返回one参与后续的相等判断,这种写法在调试while循环、需要无条件赋值后再根据新值决定分支走向时很实用。

Python的替代实现

Python不支持C++这种逗号表达式的语法,但从Python 3.8版本开始,引入了海象运算符:=,可以直接在表达式内部完成变量赋值并返回值,完全覆盖上述场景,且可读性更强:

对应if场景的写法

import random

def random_uint8t():
    return random.randint(0, 255)

one = 0
if (one := random_uint8t()) == 255:
    print("One has the max uint8_t value")

对应while循环的场景

如果是调试while循环的需求,写法如下:

while (one := random_uint8t()) != 255:
    print(f"Current value: {one}, waiting for 255...")
print("Got 255!")

内容的提问来源于stack exchange,提问作者tim687

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 16:07:08