在 python 中选择一个没有 if 语句的函数

chosing a function without if statement in python

假设有 200 个函数,代表 200 种解决问题或计算类似问题的方法

def A():
   ...
   
def B():
   ...
.
.
.

并且该方法将被选为输入参数,这意味着用户决定使用哪种方法,将其作为参数给出,而 运行 程序喜欢 function/method A 的“A”。 如何在不检查 python.

中每个函数名称的情况下选择该函数

您可以使用字典直接访问您在 O(1) 复杂性中需要的功能。例如:

def A(x):
   pass

def B(x):
   pass

func_map = {"A": A, "B": B}

假设您将用户输入存储在一个变量chosen_func中,然后对select和运行正确的函数,执行以下操作:

func_map[chosen_func](x)

示例:

In [1]: def A(x): 
   ...:     return x + x 
 
In [2]: def B(x): 
   ...:     return x * x  

In [3]: func_map = {"A": A, "B": B}

In [4]: func_map["A"](10)
Out[4]: 20

In [5]: func_map["B"](10)
Out[5]: 100