Refactoring long statement in Python
I have a very long conditio开发者_如何转开发nal statement for deciding what action to take for a pair of variables a and b.
action = 0 if (a==0) else 1 if (a>1 and b==1) else 2 if (a==1 and b>1) else 3 if (a>1 and b>1) else -1
While it is nice with the compactness (in lines;) ) of this statement, it must exist a more elegant way to do this?
if a==0:
action = 0
elif a>1 and b==1:
action = 1
elif a==1 and b>1:
action = 2
elif a>1 and b>1:
action = 3
else:
action = -1
From the Zen of Python (excerpts):
Simple is better than complex.
Flat is better than nested.
Readability counts.
If a and b both have known, small, integer ranges, you could make a dict. Say they're both always 0,1, or 2:
actionTable = { (0,0): 0, (0,1): 0, (0,2): 0,
(1,0):-1, (1,1):-1, (1,2): 2,
(2,0):-1, (2,1): 1, (2,2): 3 }
return actionTable[ (a,b) ]
But this is a little bit opaque, unscalable, and hard to maintain. If the action table is big and complex and able to be generated programmatically, though, it's a useful technique for the toolbox.
精彩评论