python - 在 Python 中重构长语句

标签 python refactoring if-statement conditional-statements

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

相关文章:

javascript - 这个 if 语句可以是一个 switch 语句并且更漂亮或更简单吗?

c# - 使用 Double 数据类型传输 Money 值

python - Pandas - 使用列作为偏移量的日期差异

python - 从字符串中选择数据框行的条件

java - 如何防止类型删除?

c++ - 检查 3 个成对字母的实例

Python:当 False 时继续执行脚本的 if/elif 函数?

python - Python 实例变量是线程安全的吗?

python - 如何使用 PyCharm 在 Django 测试中运行 celery

java - If 语句不适用于 Getter 和 Setter 方法