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

Python如何仅替换多个变量中值为None的项而非全部替换

代码修改方案

你现有代码的判断逻辑是只要变量组中存在任意一个None,就将所有变量统一设置为"none",这是所有值都被错误替换的原因。你只需要对每个变量单独做None判断替换即可,修改参考如下:

写法1:直接逐个处理(适合变量较少的场景)

# 读取所有单元格原始值
DU = sheet['B18'].value
bl_n = sheet['G17'].value
incoterm = sheet['B23'].value
transporter = sheet['G23'].value

# 仅替换值为None的变量
DU = DU if DU is not None else "none"
bl_n = bl_n if bl_n is not None else "none"
incoterm = incoterm if incoterm is not None else "none"
transporter = transporter if transporter is not None else "none"

写法2:批量处理(适合变量较多的场景,减少重复代码)

# 定义变量名和对应单元格位置的映射
cell_mapping = {
    "DU": "B18",
    "bl_n": "G17",
    "incoterm": "B23",
    "transporter": "G23"
}

result = {}
for var_name, cell_pos in cell_mapping.items():
    raw_value = sheet[cell_pos].value
    result[var_name] = raw_value if raw_value is not None else "none"

# 后续使用变量直接从result中取值即可,示例:
# DU = result["DU"]
# bl_n = result["bl_n"]

以上两种写法都可以实现仅将值为None的变量替换为字符串"none",保留其他变量的原始值,符合你期望的输出效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 13:09:03