问题描述
经过一番研究,我发现了以下问题(, 2 )关于变量.同样,我想知道是否可以在Python中以 string 的形式获取列表的 name ,例如:
After a bit of research I found these questions (1, 2) about variables. Similarly, I would like to know if it is possible to get the name of a list as a string in Python, for example:
对于列表lst = ['a', 'b', 'c']
,类似于 get_name_of_list_as_string(lst)
for a list lst = ['a', 'b', 'c']
, a method like get_name_of_list_as_string(lst)
应返回'lst' # String
.
在Python中是否有可能实现这样的目标?
Is something like that even possible in Python, and if so, how exactly?
推荐答案
这是不可能的;名称保留对对象的引用,但对象不保留对引用对象的名称(如果有)的引用.这是一种单向信息流.请记住,并非所有对象甚至都具有名称,并且许多对象都具有多个名称,因此,即使您通过堆栈检查进行了可怕的尝试来尝试启发式地找到名称,get_name_of_list_as_string([])
也会失败,x = [[]]
,get_name_of_list_as_string(x[0])
.
It's not possible; names hold references to objects, but objects do not hold references to the name(s) (if any) which reference them. It's a one-way flow of information. Remember, not all objects even have names, and many objects have more than one, so even if you did terrible things with stack inspection to try to find the name heuristically, get_name_of_list_as_string([])
is going to fail, as will x = [[]]
, get_name_of_list_as_string(x[0])
.
这篇关于在Python中以字符串形式获取列表名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!