PyCharm的“simplify chained comparison”是什么?

35 浏览
0 Comments

PyCharm的“simplify chained comparison”是什么?

我有以下函数,PyCharm在elif语句上发出了警告,提到了“simplify chained comparison”。代码可以正常工作,我得到了我想要的对象,只是想知道这个警告是什么意思,以及如何更好地写代码?

     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

admin 更改状态以发布 2023年5月21日
0
0 Comments

更简化的方法链调用,使代码更清晰。请看下面

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

0
0 Comments

应该归功于@mhlester,指出您可以从条件中省略>=子句,因为它们已经是隐含的,因为您正在使用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'))

0