Python 链式比较

3 投票
4 回答
1503 浏览
提问于 2025-04-18 08:25

我有这段代码:

if self.date: # check date is not NoneType
    if self.live and self.date <= now and self.date >= now:
         return True
return False

我的开发环境(IDE)提示:这看起来应该可以简化,也就是说可以使用Python的链式比较。

什么是链式比较,怎么简化呢?

4 个回答

0

要检查 x 是否大于 5 且小于 20,你可以使用一种叫做简化链式比较的方法,也就是:

x = 10
if 5 < x < 20:
   # yes, x is superior to 5 and x is inferior to 20
   # it's the same as: if x > 5 and x < 20:

上面的例子很简单,但我想这会帮助新手们开始了解在 python 中的简化链式比较

1

你的代码可以简化成:

return self.date and self.live and self.date == now

原因如下:

  1. now <= self.date <= now 在数学上等同于 self.date == now
  2. 如果你根据某个条件是否为真来返回一个布尔值(真或假),那么直接返回这个条件表达式的结果也是一样的。

至于简化 a <= b and b <= c:这和 a <= b <= c 是一样的;而且这实际上适用于任何其他运算符。

4
self.age <= now and self.age >= now

可以简化为:

now <= self.age <= now

但是因为它只有在 self.age 等于 now 时才为真,所以我们可以把整个算法简化为:

if self.date and self.live and self.age==now:
   return True
return False

如果你想检查年龄是否在某个范围内,可以使用连锁比较:

if lower<=self.age<=Upper:
     ...

或者:

if self.age in range(Lower, Upper+1):
     ...
6

下面是一个连锁比较的例子。

age = 25

if 18 < age <= 25:
    print('Chained comparison!')

需要注意的是,从底层来看,这和下面的写法是完全一样,只是看起来更美观。

age = 25

if 18 < age and age <= 25:
    print('Chained comparison!')

撰写回答