由于Python没有switch语句,那我应该使用什么?

12

可能重复:
Python中替换switch语句的方法?

我正在用Python制作一个基于控制台的应用程序,我想使用Switch语句来处理用户选择菜单选项。

请问有什么建议吗?谢谢!


这是所有这些的副本:http://stackoverflow.com/search?q=%5Bpython%5D+switch。 - S.Lott
自 Python 3.10 开始,有一种名为“结构模式匹配”的新的 match/case 语法。 - Robson
3个回答

13

有两种选择,第一种是标准的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()

你能给一个简单的例子来说明如何使用字典映射吗?Space_Cowboy的例子不是很清晰。 - delete
1
@sergio:假设你有 openercloser 两个函数,用于打开和关闭窗口。为了根据字符串调用它们中的一个函数,可以使用以下方法:switcher = {"open": opener, "close": closer} 将这些实际的函数存储到一个字典中。然后,你只需要执行 switcher[choice]() 即可。 - Katriel

9
使用字典将输入映射到函数。
switchdict = { "inputA":AHandler, "inputB":BHandler}

这里的处理程序可以是任何可调用对象。然后您可以这样使用它:

switchdict[input]()

9

调度表,或者说字典。

你将菜单选择的键(即值)映射到执行所选操作的函数:

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!")
menuchoices['q']()

记得验证您的输入!:)


(请注意,此处的HTML标签已保留)

3
那段代码太性感了,我想给它穿上内衣,在《花花公子》上摆姿势。+1 - delete
(1) 顺便说一下,the_input in menu_choices 是一种廉价的验证方法,可以确保与实际选项同步。 (2) 所有示例处理程序都返回 None,所以在运行示例后不必打扰警方 ;) (3) 像往常一样,在 Python 2 中使用 raw_input 而不是 input - user395760

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接