Ama*_*ria 1 python dictionary function list python-3.x
我必须通过从用户那里获取有关将作为字符串执行的操作的输入来执行多项操作。所以我在考虑使用一个字典,其中函数名是键,值是函数本身。我还想将参数传递给函数。有没有办法做到这一点?这就是我想要做的:
a = [] # an empty list
inp = input() # which function to apply?
arg = int(input()) # the argument corresponding to the function.
# a dictionary mapping all the functions to the names
func_dict = {"append":a.append(), "pop":a.pop(), "extend": a.extend()}
Run Code Online (Sandbox Code Playgroud)
我知道这行不通,我也想给出用户输入的参数。有没有办法做到这一点?
谢谢。
小智 7
只需()从函数中删除:
a = [] # an empty list
inp = input() # which function to apply?
arg = int(input()) # the argument corresponding to the function.
# a dictionary mapping all the functions to the names
func_dict = {"append":a.append, "pop":a.pop, "extend": a.extend}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您将获得函数的引用,而不是其结果。
编辑:然后调用函数,使用func_dict['append'](arg). 请注意,如果您的函数具有不同数量的参数,则此解决方案可能会失败,因此您可能必须在调用函数之前进行检查。