压缩 if 语句

Compacting an if statement

我想把这个 if 语句写得尽可能紧凑(避免重复代码)

if length == 10 if boolean is False or length == 13 if boolean is True:

PyCharm不喜欢的部分是

if boolean is True

它要求一个冒号。

PyCharm不允许我运行吧。有没有人对此有一个很好的紧凑解决方案?

认为你的意思

if (not boolean and length == 10) or (boolean and length == 13):

括号不是必需的,但我认为它们有助于提高可读性。 @jonsharpe 的解决方案更短,只需要评估 boolean 一次,但它可能更难阅读,特别是如果您不熟悉 Python 的三元表达式。

从不 使用 is 进行相等比较(这就是 == 的作用),但是布尔类型永远不应该与 [=14= 显式比较] 或 False 无论如何。

您可以使用 conditional expression(也称为 "ternary")来更简洁地写出来:

if length == 13 if boolean else length == 10:

或者,等价地:

if length == (13 if boolean else 10):

根据文档:

The expression x if C else y first evaluates the condition, C (not x); if C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.