比If Else更聪明

use*_*351 3 python if-statement

我正在尝试切换(各种)命令.

if 'Who' in line.split()[:3]:
    Who(line)   
elif 'Where' in line.split()[:3]:
    Where(line)
elif 'What' in line.split()[:3]:
    What(line)
elif 'When' in line.split()[:3]:
    When(line)
elif 'How' in line.split()[:3]:
    How(line)
elif "Make" in line.split()[:3]:
    Make(line)
elif "Can You" in line.split()[:3]:
    CY(line)
else:
    print("OK")
Run Code Online (Sandbox Code Playgroud)

所以解释.如果Who,What等等在命令的前3个字中,则它执行相应的功能.我只是想知道除了很多之外是否有更聪明的方法来做到这一点if,elif并且else

pla*_*mut 9

尝试创建一个字典,其中键是命令名称和实际命令功能的值.例:

def who():
    ...

def where():
    ...

def default_command():
    ...

commands = {
    'who': who,
    'where': where,
    ...
}

# usage
cmd_name = line.split()[:3][0]  # or use all commands in the list
command_function = commands.get(cmd_name, default_command)
command_function()  # execute command
Run Code Online (Sandbox Code Playgroud)

  • 但是,`cmd_name`是一个字符串列表,因此我们不能使用它来索引字典. (5认同)