【问题标题】:what is PyCharm "simplify chained comparison"什么是 PyCharm“简化链式比较”
【发布时间】:2014-03-31 09:25:39
【问题描述】:

我有以下功能,PyCharm 在elif 关于“简化链式比较”的声明中提醒我。代码有效,我得到了我想要的对象,只是想知道警告以及如何使它变得更好?

     def preferred_contacts(self):
         x = random.randint(0, 100)
         email = u'E'
         text = u'M'
         phone = u'P'
         letter = u'L'
         none = u'N'

         if x < 25:
            return email
         elif x >= 26 and x <= 50:
            return text
         elif x >= 51 and x <= 75:
            return phone
         elif x >= 76 and x <= 100:
            return letter
         else:
            return none

【问题讨论】:

  • 您当然可以删除所有 x &gt;= 比较,因为达到 elif 后,它已经被证明不符合之前的条件
  • 另外,你会很高兴得知这一点:elif 76 &lt;= x &lt;= 100: 你希望它做什么。
  • 真的你也不需要and 操作; elif 26 &lt;= x &lt;= 50等等……
  • 另外,这将永远不会返回 none,因为您将 x 限制在 100,而 100 将返回 letter

标签: python python-2.7 pycharm


【解决方案1】:

@mhlester 应该注意到您可以从条件中删除 &gt;= 子句,因为它们已经是隐含的,因为您使用的是 elif。但是,如果您愿意,您也可以通过将数据放在一个元组中然后对其进行索引来压缩更多内容。

return ('E', 'M', 'P', 'L', 'N')[x / 25] # This assumes x has an upper bound of 124 or less.

当然,在这种特殊情况下,您可以让您的生活更加简单。

return random.choice(('E', 'M', 'P', 'L', 'N'))

【讨论】:

【解决方案2】:

简化的链式调用带来更简洁的代码。见下文

def preferred_contacts(self):
x = random.randint(0, 100)
email = u'E'
text = u'M'
phone = u'P'
letter = u'L'
none = u'N'

if x < 25:
    return email
elif 26 <= x <= 50: # reads as "x is between 26 and 50, inclusive
    return text
elif 51 <= x <= 75: # reads as "x is between 51 and 75, inclusive
    return phone
elif 76 <= x <= 100: # reads as "x is between 76 and 100, inclusive
    return letter
else:
    return none

【讨论】:

    猜你喜欢
    • 2017-11-23
    • 2014-12-17
    • 2017-03-21
    • 2018-12-22
    • 1970-01-01
    • 2014-05-17
    • 1970-01-01
    相关资源
    最近更新 更多