【问题标题】:Python chained comparison [duplicate]Python链式比较[重复]
【发布时间】:2014-07-23 23:23:34
【问题描述】:

我有这个代码:

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 链式比较。

什么是链式比较,如何简化?

【问题讨论】:

  • 不是答案,但您确定self.age 永远不会为0?因为那样第一次比较也会是假的;不仅仅是None
  • @Evert,是的,没错,让我更新 OP。
  • self.date &lt;= now and self.date &gt;= now 不就是说self.date == now吗?
  • @njzk2 是不好的例子,但我现在明白答案了。

标签: python django


【解决方案1】:

要检查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中的简化链比较

【讨论】:

    【解决方案2】:

    您的代码可以而且应该简化为:

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

    这是因为:

    1. now &lt;= self.date &lt;= now 在数学上等于 self.date == now
    2. 如果根据条件是否为真返回布尔值,则与仅返回对条件表达式本身求值的结果相同。

    关于减少a &lt;= b and b&lt;= c:同a &lt;= b &lt;= c;这实际上适用于任何其他运营商。

    【讨论】:

      【解决方案3】:

      链式比较的示例如下所示。

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

      请注意,在封面下面是exactly the same,如下所示,它看起来更好。

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

      【讨论】:

        【解决方案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):
             ...
        

        【讨论】:

          猜你喜欢
          • 2017-03-21
          • 2020-01-24
          • 2017-11-23
          • 1970-01-01
          • 2018-03-01
          • 1970-01-01
          • 1970-01-01
          • 2019-05-20
          • 2021-11-18
          相关资源
          最近更新 更多