这是在运行时优化的,就像您请求的那样…(尽管很可能不需要)
下面是一个简单的代码位,它将获取映射到函数的命令输入字典,并生成映射到同一函数的所有非重复子命令的输出字典。
因此,当您启动服务时运行此函数,然后您可以进行100%的优化查找。我相信有一个更聪明的方法来做到这一点,所以请随时编辑。commands = {
'log': log_function,
'exit': exit_function,
'foo': foo_function,
'line': line_function,
}
cmap = {}
kill = set()
for command in commands:
for pos in range(len(1,command)):
subcommand = command[0:pos]
if subcommand in cmap:
kill.add(subcommand)
del(cmap[subcommand])
if subcommand not in kill:
cmap[subcommand] = commands[command]
#cmap now is the following - notice the duplicate prefixes removed?
{
'lo': log_function,
'log': log_function,
'e': exit_function,
'ex': exit_function,
'exi': exit_function,
'exit': exit_function,
'f' : foo_function,
'fo' : foo_function,
'foo' : foo_function,
'li' : line_function,
'lin' : line_function,
'line' : line_function,
}