简体   繁体   中英

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

I'm working on a terminal application written in python 3.7 . Currently, when a command is inputted, it is passed through a function that looks like this:

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

and each function looks like this:

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

I haven't tried other methods as I am unsure what to use - and I'm using this method because I saw a piece of code that used it a long time ago.

What would be the best (most efficient/optimised) way to do this? This seems very wasteful and slow and with more functions, ones lower down the list could take noticeable time to be reached.

I would use a dictionary where the command-strings are the keys and the functions are the values. Dictionary will have a log(n) search time, and should keep the tree structure balanced. So having d as the dict , defined similar to this:

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

And of course:

def myFunc1(args..):
    ...

def myFunc2(args..):
    ...

We end up with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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