使用字典映射。
代码示例:
原始代码:
if x == 'a': #execute a elif x == 'b': #execute b elif x == 'c': #execute c #...and so on
改进后的代码:
actions = { 'a': #execute a, 'b': #execute b, 'c': #execute c, #... } actions.get(x, default_action)()
其中,default_action是在x不在actions字典中时执行的默认操作。这就是使用字典映射的基本思路。这种方法比长串的if-else语句更易读易维护,而且可以随时添加更多的操作。