【问题标题】:How to call a function whose name is given by the user through Python dictionary w/o if-elif statements如何通过没有 if-elif 语句的 Python 字典调用用户给出名称的函数
【发布时间】:2020-05-11 21:26:21
【问题描述】:

我正在尝试编写一个程序,该程序向用户请求命令和一堆参数并执行它。此外,尝试通过使用 python 字典来提高效率。这是我的代码:

command, *args = input().split()
args = list(map(int, args))
options = {'a': print(args[0]),
           'b': print(args[1]),
          }
options.get(command)

但是,当我在输入中输入 'a 1 2' 时,程序会同时编译 command acommand b。这是为什么?我可以修复它吗?提前谢谢!

【问题讨论】:

  • 在创建字典时执行打印命令。如果您不希望这样,请不要在字典中使用 print。
  • 您甚至可以省略options.get(command) 行,将获得相同的输出...
  • 如果您想将参数传递给程序,请查看内置的“argparse”库。
  • 谢谢大家!我现在明白了。
  • 只是好奇为什么要在字典中打印?

标签: python function dictionary


【解决方案1】:

正如有人指出的那样,您可以使用eval。然而,更好的方法是将函数作为字典中的值传递并在检索期间调用它们。最简单的方法是使用lambda 创建一个简单的内联函数。

使用您的代码,这将是这样的:

command, *args = input().split()
args = list(map(int, args))
options = {'a': lambda args: print(args[0]),
           'b': lambda args: print(args[1]),
          }
options.get(command)(args)

如果您不熟悉 lambda 表达式,这只是创建简单函数的一种更简单的方法。例如 lambda args: print(args[1]) 计算结果为

def func(args):
    print(args[1])

【讨论】:

    【解决方案2】:

    您的问题可以通过以下方式回答:

    command, *args = input().split()
    args = list(map(int, args))
    options = {'a': (print, args[0]),
               'b': (print, args[1]),
              }
    
    func, arg = options.get(command)
    func(arg)
    

    现在,输入b 123 23,只会打印23

    【讨论】:

      猜你喜欢
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-30
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      • 1970-01-01
      相关资源
      最近更新 更多