【问题标题】:What's the most efficient way to run through keywords/functions?遍历关键字/函数的最有效方法是什么?
【发布时间】:2019-07-25 20:13:23
【问题描述】:

我正在开发一个用 python 3.7 编写的终端应用程序。目前,当输入命令时,它会通过如下所示的函数传递:

def execute(command):
    if command is None or command.isspace() or command == "":
        terminal()

    command = command.split(" ")
    command = list(command)
    command[0] = command[0].lower()

    var(command)
    iftrue(command)
    ... etc

每个函数看起来像这样:

def func(command):
    if command[0] == "func":
        function code blah blah blah

我没有尝试过其他方法,因为我不确定该使用什么 - 我正在使用这种方法,因为我看到一段很久以前使用过的代码。

最好的(最有效/优化)方法是什么?这似乎非常浪费和缓慢,而且功能更多,列表中较低的功能可能需要相当长的时间才能达到。

【问题讨论】:

  • 您可能应该为这些任务使用专用模块,例如 argparsecmd
  • @DeepSpace 你能详细说明一下吗?
  • 对这些模块进行一些研究,您会发现比我在评论/答案docs.python.org/3/library/argparse.htmldocs.python.org/3.7/library/cmd.html 中无法容纳的更多信息
  • ...我只是在@DeepSpace 模块列表中添加了一些第 3 方模块:clickinvokedocopt
  • 不管怎样,我在工作中使用click 效果很好。

标签: python python-3.x performance optimization


【解决方案1】:

我会使用一个字典,其中命令字符串是键,函数是值。字典将有一个 log(n) 搜索时间,并且应该保持树结构的平衡。所以将d 定义为dict,定义类似于:

d = {'func1': myFunc1, 'func2': MyFunc2...}

当然还有:

def myFunc1(args..):
    ...

def myFunc2(args..):
    ...

我们最终得到:

if cmd in d:
    d[cmd](args...)

【讨论】:

  • "字典将有一个 log(n) 搜索时间" 也许在非常罕见的大量哈希冲突的情况下......除了字典有 O(1) 查找
  • 我最终使用了这种方法。效果很好
猜你喜欢
  • 1970-01-01
  • 2021-03-28
  • 1970-01-01
  • 1970-01-01
  • 2016-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多