如何获取列表名称作为参数传递给 python 中的函数

how to get the list name passed as a parameter to a function in python

我有下面的功能,我只是想return "list_" 从这里实现,但是无法实现。任何帮助将不胜感激。

import inspect

def f(*x, **y):
    _,_,_,lo=inspect.getargvalues(inspect.currentframe())
    print(list(lo.values()))        

list_=[1,2,3,4]
f(list_)

您可以遍历存储在 globals() 和 return 变量名称中的全局变量,其值等于作为 x[0] 提供的参数。在这里,我们使用 next() 在找到匹配项后立即停止迭代 globals() 和 return 我们的值。

def f(*x, **y):
    return next(i for i in globals() if globals()[i] == x[0])

list_ = [1,2,3,4]
print(f(list_)) # -> "list_"

或使用inspect

def f(*x, **y):
    callers_local_vars = inspect.currentframe().f_back.f_locals.items()
    return next(var_name for var_name, var_val in callers_local_vars if var_val is x[0])

print(f(list_)) # -> "list_"