python - Simulating 'else' in dictionary switch statements

会有一股神秘感。 提交于 2019-12-08 19:13:48

问题


I'm working on a project which used a load of If, Elif, Elif, ...Else structures, which I later changed for switch-like statements, as shown here and here.

How would I go about adding a general "Hey, that option doesn't exist" case similar to an Else in an If, Elif, Else statement - something that gets executed if none of the Ifs or Elifs get to run?


回答1:


You could catch the KeyError error that ensues when a value is not found in the map, and return or process there a default value. For example, with n = 3 this piece of code:

if n == 1:
    print 'one'
elif n == 2:
    print 'two'
else:
    print 'too big!'

Becomes this:

choices = {1:'one', 2:'two'}
try:
    print choices[n]
except KeyError:
    print 'too big!'

Either way, 'too big!' gets printed on the console.




回答2:


If the else is really not an exceptional situation, would it not be better to use the optional parameter for get?

>>> choices = {1:'one', 2:'two'}
>>> print choices.get(n, 'too big!')

>>> n = 1
>>> print choices.get(n, 'too big!')
one

>>> n = 5
>>> print choices.get(n, 'too big!')
too big!



回答3:


The first article you linked to had a very clean solution:

response_map = {
    "this": do_this_with,
    "that": do_that_with,
    "huh": duh
}
response_map.get( response, prevent_horrible_crash )( data )

This will call prevent_horrible_crash if response is not one of the three choices listed in response_map.




回答4:


Let's say you have a function f(a,b) and different setups of parameters according to the value of some variable x. So you want to execute f with a=1 and b=3 if x='Monday' and if x='Saturday' you want to execute f with a=5 and b=9. Otherwise you will print that such value of x is not supported.

I would do

from functools import partial
def f(a,b):
 print("A is %s and B is %s" % (a,b))

def main(x):
 switcher = {
             "Monday": partial(f,a=1, b=3),
             "Saturday": partial(f, a=5, b=9)
            }
 if x not in switcher.keys():
  print("X value not supported")
  return

 switcher[x]()

this way f is not executed on declaration of switcher but at the last line.



来源:https://stackoverflow.com/questions/15514180/python-simulating-else-in-dictionary-switch-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!