【问题标题】:Python 3 change the names dynamicallyPython 3 动态更改名称
【发布时间】:2018-07-17 23:58:55
【问题描述】:
import numpy as np
Method_name = "method_a"
#Method_name = "method_b"

def method_a (x, y):
    result = x + y
    return result

def method_b (x, y):
    result = x * y
    return result

result_method_a = np.zeros((0,1))
result_method_b = np.zeros((0,1))

x1 = 1
x2 = 5

for i in range (10):

    result = method_a(x1, x2)
    result +=1
    print (result)
    result_method_a = np.vstack((result_method_a, result))

    x1 += 1
    x2 += 5

如果我激活 method_a 或 method_b,有什么方法可以动态更改名称

例如: 如果我取消注释该行:

Method_name = "method_b"

然后我会得到:

result = method_b(x1, x2)

和:

result_method_b = np.vstack((result_method_b, result))

等等

这只是一个小例子。

【问题讨论】:

    标签: arrays python-3.x numpy dynamic names


    【解决方案1】:

    您可以使用内置的eval() 函数。

    Method_name_a = "method_a"
    Method_name_b = "method_b"
    
    method_to_run = Method_name_a # change this as needed
    
    def method_a (x, y):
        result = x + y
        return result
    
    def method_b (x, y):
        result = x * y
        return result
    
    x1 = 1
    x2 = 5
    
    res = eval(method_to_run)(x1, x2)
    print(res)
    

    您可以在使用 numpy 函数时重新创建相同的内容。

    但是,我建议不要使用eval(),尤其是当您将用户输入作为参数传递时。您可以在线阅读更多相关信息。

    另一种解决方案

    Method_name_a = "method_a"
    Method_name_b = "method_b"
    
    def method_a (x, y):
        result = x + y
        return result
    
    def method_b (x, y):
        result = x * y
        return result
    
    method_mapping = {
        Method_name_a: method_a,
        Method_name_b: method_b
    }
    
    method_to_run = Method_name_a
    
    # You could also set a default function to run in case
    # the desired function is not available
    method = method_mapping.get(method_to_run) 
    
    x, y = 3, 5
    res = method(x, y)
    print(res)
    

    这个解决方案是安全的,我更喜欢它而不是使用 eval() 函数的那个​​。

    【讨论】:

      【解决方案2】:

      不要关注名称,而要关注函数对象。

      if True:
          method = method_a
      else:
          method = method_b
      
      result = method((x1,x2)
      

      可以根据 if 语句运行任一函数。

      函数是 Python 中的“一等”对象,可以像数字一样分配、放入列表等。

      将字符串与函数连接起来最简单的方法是使用字典:

      dd = {'foo_a':method_a, 'foo_b':method_a, 'bar_a': method_b}
      

      另外,最好构建一个数组列表并应用vstack一次:

      alist = []
      for i in range...:
         alist.append(anarray)
      arr = np.vstack(alist)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-28
        • 2018-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多