繁体   English   中英

运行关键字/函数的最有效方法是什么?

[英]What's the most efficient way to run through keywords/functions?

我正在开发一个用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

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

什么是最好(最有效/最优化)的方法来做到这一点? 这似乎非常浪费和缓慢,并且功能更多,列表中较低的功能可能需要花费大量时间才能到达。

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

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

而且当然:

def myFunc1(args..):
    ...

def myFunc2(args..):
    ...

我们最终得到:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM