Skip to main content
 首页 » 编程设计

python之在 Python 中重构长语句

2025年05月04日9shangdawei

我有一个很长的条件语句来决定对一对变量 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.