我已经读了如何获得一个函数名作为字符串?。
如何对变量做同样的事情呢?与函数相反,Python变量没有__name__属性。
换句话说,如果我有一个变量,比如:
foo = dict()
foo['bar'] = 2
我正在寻找一个函数/属性,例如retrieve_name(),以便从这个列表中创建一个DataFrame in Pandas,其中列名由实际字典的名称给出:
# List of dictionaries for my DataFrame
list_of_dicts = [n_jobs, users, queues, priorities]
columns = [retrieve_name(d) for d in list_of_dicts]
我有一个方法,虽然不是最有效的…它的工作原理!(它不涉及任何花哨的模块)。
基本上,它将你的变量ID与globals()变量ID进行比较,然后返回匹配的名称。
def getVariableName(variable, globalVariables=globals().copy()):
""" Get Variable Name as String by comparing its ID to globals() Variables' IDs
args:
variable(var): Variable to find name for (Obviously this variable has to exist)
kwargs:
globalVariables(dict): Copy of the globals() dict (Adding to Kwargs allows this function to work properly when imported from another .py)
"""
for globalVariable in globalVariables:
if id(variable) == id(globalVariables[globalVariable]): # If our Variable's ID matches this Global Variable's ID...
return globalVariable # Return its name from the Globals() dict
如果有两个值相同的变量,前面的一些情况会失败。所以提醒它很方便:
定义函数:
# Variable to string of variable name
def var_name(variable,i=0):
results = []
for name in globals():
if eval(name) == variable:
results.append(name)
if len(results) > 1:
print('Warning:' )
print(' var_name() has found',len(results), 'possible outcomes.')
print(' Please choose the suitable parameter "i". Where "i" is the index')
print(' that matches your choice from the list below.')
print(' ',results) ; print('')
return results[i]
Use:
var_1 = 10
var_name(var_1) # Output will be "var_1"
如果你有两个相同值的变量,比如var_1 = 8和var_2 = 8,那么就会出现一个警告。
var_1 = 8
var_2 = 8
var_name(var_2) # Output will be "var_1" too but Warning will appear