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

12 投票
3 回答
6709 浏览
提问于 2025-04-16 05:48

可能重复的问题:
Python中可以替代switch语句的方式?

我正在用Python做一个小的控制台应用程序,我想用switch语句来处理用户在菜单中选择的选项。

你们这些老手有什么建议吗?谢谢!

3 个回答

9

用字典来把输入和函数对应起来。

switchdict = { "inputA":AHandler, "inputB":BHandler}

这里的处理器可以是任何可以调用的东西。然后你可以这样使用它:

switchdict[input]()
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()
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']()

记得要验证你的输入哦! :)

撰写回答