【发布时间】:2011-04-28 01:49:50
【问题描述】:
我正在用 Python 制作一个基于控制台的小应用程序,我想使用 Switch 语句来处理用户对菜单选择的选择。
你的兽医建议我用什么。谢谢!
【问题讨论】:
-
从 Python 3.10 开始,有一个新的
match/case语法称为“结构模式匹配”。
我正在用 Python 制作一个基于控制台的小应用程序,我想使用 Switch 语句来处理用户对菜单选择的选择。
你的兽医建议我用什么。谢谢!
【问题讨论】:
match/case 语法称为“结构模式匹配”。
有两种选择,第一种是标准的if ... elif ...链。另一种是将选择映射到可调用对象的字典(函数是子集)。取决于你在做什么,哪个更好。
elif 链
selection = get_input()
if selection == 'option1':
handle_option1()
elif selection == 'option2':
handle_option2()
elif selection == 'option3':
some = code + that
[does(something) for something in range(0, 3)]
else:
I_dont_understand_you()
字典:
# Somewhere in your program setup...
def handle_option3():
some = code + that
[does(something) for something in range(0, 3)]
seldict = {
'option1': handle_option1,
'option2': handle_option2,
'option3': handle_option3
}
# later on
selection = get_input()
callable = seldict.get(selection)
if callable is None:
I_dont_understand_you()
else:
callable()
【讨论】:
opener 和closer,比如说打开和关闭一个窗口。然后根据字符串调用其中一个,执行switcher = {"open": opener, "close": closer} 以便您在dict 中拥有实际功能。然后你可以做switcher[choice]()。
使用字典将输入映射到函数。
switchdict = { "inputA":AHandler, "inputB":BHandler}
处理程序可以是任何可调用的。然后你像这样使用它:
switchdict[input]()
【讨论】:
调度表,或者更确切地说是字典。
您也可以映射键。菜单选择的值到执行所述选择的功能:
def AddRecordHandler():
print("added")
def DeleteRecordHandler():
print("deleted")
def CreateDatabaseHandler():
print("done")
def FlushToDiskHandler():
print("i feel flushed")
def SearchHandler():
print("not found")
def CleanupAndQuit():
print("byez")
menuchoices = {'a':AddRecordHandler, 'd':DeleteRecordHandler, 'c':CreateDatabaseHandler, 'f':FlushToDiskHandler, 's':SearchHandler, 'q':CleanupAndQuit}
ret = menuchoices[input()]()
if ret is None:
print("Something went wrong! Call the police!")
menuchoices['q']()
记得验证您的输入! :)
【讨论】:
the_input in menu_choices 是一种廉价的验证,可以保证与实际选择同步。 (2) 所有示例处理程序都返回None,因此在运行示例后不要打扰警察;) (3) 一如既往,在 Python 2 中使用raw_input 而不是input。