【问题标题】:How to assign a function to a String and use some of the string as parameter for the function如何将函数分配给字符串并使用某些字符串作为函数的参数
【发布时间】:2017-09-14 10:54:24
【问题描述】:

我在搞清楚一些事情时遇到了一些麻烦。 假设我有一个字符串列表(一个 csv、txt 或类似的东西),看起来像这样:

1)设置汽车颜色=红色

2)设置 Radio-Volume = 50%

3)汽车空调温度 = 20°C

我希望这些行中的每一行都执行我创建的一些函数。假设我创建了一些使用上面字符串中的值的函数。 例如:

def set_color(colorvalue):
  car_color= colorvalue
  print("The car has been set to: ",colorvalue)

def radio_vol(vol):
  #do something here

def set_car_ac_to(deg):
  #do something else here

等,你明白了。 什么是最好的方法,以便在解析包含文本行的 csv,txt 文件时,使用给定的参数调用它们的特定函数。 如何将函数分配给字符串并使用它的特定参数。 谢谢

【问题讨论】:

    标签: python string function csv parsing


    【解决方案1】:

    使用dict

    actions = {"Set Car color": set_color,
               "Set Radio-Volume": radio_vol, ...}
    
    command = "Set Car color"
    argument = "red"
    
    actions[command](argument)
    

    【讨论】:

      猜你喜欢
      • 2021-09-20
      • 2021-10-28
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 2018-03-14
      • 2011-12-11
      • 1970-01-01
      相关资源
      最近更新 更多