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

如何将Python变量名转为字符串并自动存入列表?

获取变量名称生成列表的实现方法

Python里没有直接的内置函数能直接拿到变量的名称(因为变量本质是对象的引用,对象本身不记录引用它的变量名),但可以通过两种常见方式实现你的需求:

方法1:遍历当前作用域筛选(适合值唯一或明确目标值的场景)

如果你的变量都指向同一个值(比如都是type(int)),可以直接遍历当前的局部作用域,筛选出对应值的变量名:

a = type(int)
b = type(int)
c = type(int)

target = type(int)
var_list = [name for name, val in locals().items() if val == target and name != "target"]
print(var_list)  # 输出: ['a', 'b', 'c']

注意:locals()会返回当前作用域的所有变量,这里额外加了name != "target"来排除我们定义的目标值变量,避免被误加入列表。

方法2:用inspect模块精准匹配(适合任意场景)

如果变量值可能重复,或者你想精准指定要获取名称的变量,可以借助inspect模块获取调用栈的局部变量,通过对象的内存地址匹配:

import inspect

def get_var_names(*variables):
    # 获取调用者的作用域
    caller_frame = inspect.currentframe().f_back
    names = []
    for var in variables:
        # 遍历调用者的局部变量,找到与目标对象内存地址一致的变量名
        for name, val in caller_frame.f_locals.items():
            if val is var:
                names.append(name)
                break
    return names

a = type(int)
b = type(int)
c = type(int)

var_list = get_var_names(a, b, c)
print(var_list)  # 输出: ['a', 'b', 'c']

这个方法用is判断对象的内存地址,不会因为值相同而误匹配,能精准拿到你指定的变量名称。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 15:16:03