简体   繁体   English

将与定义名称对应的字符串列表转换为 Python 中的定义查找字典

[英]Converting a list of strings that corresponds to definition names into a definition lookup dictionary in Python

Is there a way to convert a list of function or definition names (strings) into a dictionary based lookup table where the key is the definition name and the value is the definition class that corresponds to the name (the definition name is the name given).有没有办法将 function 列表或定义名称(字符串)转换为基于字典的查找表,其中键是定义名称,值是与名称对应的定义 class(定义名称是给定的名称) . It has been said that the safest way is to use the lookup table approach (dictionary mapping) such as here .有人说,最安全的方法是使用查找表方法(字典映射),例如此处 However, the situation is such that the list of definition names is variable and the user/programmer is not able to directly write it into the code but rather it has to be added programmatically.然而,这种情况是定义名称列表是可变的,用户/程序员不能直接将其写入代码,而是必须以编程方式添加。

So how can I do effective the following:那么我怎样才能有效地做到以下几点:

nameList = ['methodName1','methodName2','methodName3','methodName4'] 
methodLookup = {}
for name in nameList:
        methodLookup.update({name:name.strip('\'')})

Where the dictionary value is the function not the string.其中字典值是 function 而不是字符串。

Something similar in essence to but the opposite of the following:本质上与以下内容相似但相反的内容:

for var, val in dictionary.items(): exec(var + ' = val')

I guess you could use something like this:我想你可以使用这样的东西:

def plus1(x):
    return x + 1
def plus2(x):
    return x + 2

function_list = ['plus1', 'plus2']
function_dict = {function_name: globals()[function_name] for function_name in function_list}

And then after that you can call plus1 function by:然后,您可以通过以下方式调用plus1 function:

function_dict['plus1'](5)
#6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM