gpt4 book ai didi

python - 比 If Else 更聪明

转载 作者:太空宇宙 更新时间:2023-11-03 12:27:26 25 4
gpt4 key购买 nike

我正在尝试切换(某种)命令。

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")

所以解释。如果 WhoWhat 等在命令的前 3 个单词中,则它会执行相应的功能。我只想知道除了大量的 ifelifelse 之外,是否还有更聪明的方法来做到这一点?

最佳答案

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

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

关于python - 比 If Else 更聪明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31896495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com