【问题标题】:Is there any other ways to accomplish this task in Python?有没有其他方法可以在 Python 中完成这项任务?
【发布时间】:2020-03-27 19:19:51
【问题描述】:

这可能是一个愚蠢的问题,但我想知道我是否可以使用字典或某种数组来完成这项任务?我尝试使用这样的字典,它只是调用所有函数。

我的目标是在用户输入关键字时调用特定函数,但我想避免使用那些冗长的 if 和 else 语句。

这是我尝试过的:

def Func1():
    print ("This is func1")

def Func2():
    print ("This is func2")

def Func3():
    print ("This is func3")

functions = {"/func1" : Func1(), "/func2" : Func2(), "/func3" : Func3()}

【问题讨论】:

  • 你可以留下函数对象,而不调用它们
  • 我必须创建这么多对象,对吧?有没有更有效的方法来做到这一点?

标签: python function dictionary hashmap


【解决方案1】:

制作一个包含函数objects但实际上并不调用它们的字典:

def func1():
    print("I am function 1")

# etc for func2 and func3

functions = {
    "func1": func1,
    "func2": func2,
    "func3": func3
}
answer = input("Which function do you want to call? ")
if answer in functions:
    # find the correct function object and call it
    functions[answer]()
else:
    print("I can't find that function.")

【讨论】:

    【解决方案2】:

    更简单的方法是查找与用户给出的命令对应的函数

    def Func1():
        print ("This is func1")
    
    def Func2():
        print ("This is func2")
    
    def Func3():
        print ("This is func3")
    
    functions = {"/func1" : Func1, "/func2" : Func2, "/func3" : Func3}
    user_input = input("Enter command> ")
    functions[user_input]()
    

    还要确保从字典中存储的函数中删除括号,否则它们将在脚本运行时执行。

    【讨论】:

      猜你喜欢
      • 2021-09-06
      • 2012-06-28
      • 1970-01-01
      • 1970-01-01
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多