讓主邏輯簡(jiǎn)潔易懂。
程式邏輯常出現(xiàn)分支,這時(shí)會(huì)習(xí)慣性地用 if ... elif ... else ... 的寫法。雖然這樣寫起來(lái)很直觀,卻不易讀,容易分心在雜亂的分枝里,而無(wú)法專心理解全局。
def foo(x):
if x < 0:
return False
...
return True
abs_numbers = [math.fabs(x) for x in numbers]
def x_to_y(x):
if SOME_CONDITION:
return SOME_VALUE
...
return SOME_VALUE
ys = [x_to_y(x) for x in xs]
import operator
def calculation(a, op, b):
digits = ['zero', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine']
s2n = dict(zip(digits, range(10)))
n2s = dict(zip(range(10), digits))
op_names = ['add', 'subtract', 'divide', 'multiply']
op_funcs = [operator.add, operator.sub, operator.div, operator.mul]
s2op = dict(zip(op_names, op_funcs))
result = s2op[op](s2n[a], s2n[b])
return n2s[result]
print calculation('one', 'add', 'two') # three
更多建議: