【问题标题】:Since Python doesn't have a switch statement, what should I use? [duplicate]由于 Python 没有 switch 语句,我应该使用什么? [复制]
【发布时间】:2011-04-28 01:49:50
【问题描述】:

可能重复:
Replacements for switch statement in python?

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

你的兽医建议我用什么。谢谢!

【问题讨论】:

标签: python switch-statement


【解决方案1】:

有两种选择,第一种是标准的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 的例子不太清楚。
  • @sergio:假设你有函数openercloser,比如说打开和关闭一个窗口。然后根据字符串调用其中一个,执行switcher = {"open": opener, "close": closer} 以便您在dict 中拥有实际功能。然后你可以做switcher[choice]()
【解决方案2】:

使用字典将输入映射到函数。

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

处理程序可以是任何可调用的。然后你像这样使用它:

switchdict[input]()

【讨论】:

    【解决方案3】:

    调度表,或者更确切地说是字典。

    您也可以映射键。菜单选择的值到执行所述选择的功能:

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

    记得验证您的输入! :)

    【讨论】:

    • 那个代码太性感了,我想给它内衣,让它摆在《花花公子》上。 +1
    • (1) 顺便说一句,the_input in menu_choices 是一种廉价的验证,可以保证与实际选择同步。 (2) 所有示例处理程序都返回None,因此在运行示例后不要打扰警察;) (3) 一如既往,在 Python 2 中使用raw_input 而不是input
    猜你喜欢
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 2012-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多