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

如何在Python中获取输入变量的原始名称并输出对应结果

问题描述

我想要对多个输入的数字进行比较,并以字符串类型输出结果。以下是简化版本的代码:

a = input()
b = input()
c = input()
Com = [a, b, c]

print (min(Com) + " is the smallest, the value is %s" %min(Com))

例如,当我为a、b、c分别输入1、2、3时,当前输出为:

"1 is the smallest, the value is 1"

但我实际期望的输出是:

"a is the smallest, the value is 1"

请问是否有方法可以找到值1对应的原始变量名a?

解决方案

直接用列表存储值无法关联对应的变量名,你可以改用字典来绑定变量名和对应输入值,这样就能同时获取最小值的名称和数值。

修改后的代码如下:

# 用字典存储变量名与输入值的对应关系
var_dict = {
    'a': input(),
    'b': input(),
    'c': input()
}

# 根据值找到对应的变量名(键)
min_key = min(var_dict, key=var_dict.get)
min_value = var_dict[min_key]

# 格式化输出目标结果
print(f'"{min_key} is the smallest, the value is {min_value}"')

代码说明

  • 字典var_dict将变量名(字符串形式)和输入值绑定,解决了值与名称分离的问题。
  • min(var_dict, key=var_dict.get)会依据字典的值来筛选出对应的键(即原始变量名)。
  • 使用f-string格式化输出,直接拼接变量名和值,得到预期结果。

测试输入1、2、3时,输出为:

"a is the smallest, the value is 1"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 06:02:04