我有一个很长的条件语句来决定对一对变量 a 和 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
虽然这句话的紧凑性(行;))很好,但它必须存在更优雅的方式来做到这一点吗?
最佳答案
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
来自Zen of Python (节选):
Simple is better than complex.
Flat is better than nested.
Readability counts.
关于python - 在 Python 中重构长语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3851094/