python - 在字典开关语句中模拟'else
5 个回答
2
你链接的第一篇文章提供了一个非常简单明了的解决方案:
response_map = {
"this": do_this_with,
"that": do_that_with,
"huh": duh
}
response_map.get( response, prevent_horrible_crash )( data )
如果response
的值不是response_map
中列出的三个选项之一,就会调用prevent_horrible_crash
这个函数。
9
如果else并不是一个特殊的情况,那么用可选参数来处理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!
7
当你在一个字典里找不到某个值时,会出现一个叫做 KeyError
的错误。你可以捕捉到这个错误,然后返回一个默认值或者进行其他处理。比如说,如果 n = 3
,那么这段代码:
if n == 1:
print 'one'
elif n == 2:
print 'two'
else:
print 'too big!'
就变成了这样:
choices = {1:'one', 2:'two'}
try:
print choices[n]
except KeyError:
print 'too big!'
无论哪种方式,控制台上都会打印出 'too big!'
。