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

有没有更优的Python批量打印指定变量的实现方案?

方案1:直接构造遍历列表(最稳妥,不需要依赖变量命名规则)

A_PR = 3
B_PR = 4
C_PR = 6

for model_name, value in [("A", A_PR), ("B", B_PR), ("C", C_PR)]:
    print(f"the value of the model {model_name} is: {value}")

方案2:基于命名规则自动取变量(适合变量名有统一规律的场景)

如果你的变量都是{标识}_PR的命名格式,可以直接从全局变量空间取值:

A_PR = 3
B_PR = 4
C_PR = 6

for prefix in ["A", "B", "C"]:
    value = globals()[f"{prefix}_PR"]
    print(f"the value of the model {prefix} is: {value}")

方案3:用字典存储参数(最佳实践,可维护性最高)

同类配置参数建议统一存放在字典中,后续新增/修改参数不需要调整打印逻辑:

model_params = {
    "A": 3,
    "B": 4,
    "C": 6
}

for model_name, value in model_params.items():
    print(f"the value of the model {model_name} is: {value}")

以上所有方案的输出和你原手写三段print的效果完全一致。

内容的提问来源于stack exchange,提问作者Marco Andres Alarcon Sierra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:27:03