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

Since Python doesn't have a switch statement, what should I use?

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
Replacements for switch statement in python?

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

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


有两种选择,第一种是标准的if ... elif ...链。另一个是字典将选择映射到可调用文件(函数的子集)。具体取决于你在做什么,哪个更好。

ELIF链

1
2
3
4
5
6
7
8
9
10
 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()

字典:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 # 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()


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

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

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

1
switchdict[input]()


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

你把钥匙也标在地图上。执行上述选择的功能的菜单选择值:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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']()

记住要验证您的输入!:)