what is PyCharm “simplify chained comparison”
我有以下功能,Pycharm正在提醒我关于"简化链接比较"的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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 |
@mhlester应该注意到你可以从条件中删除
1 | return ('E', 'M', 'P', 'L', 'N')[x / 25] # This assumes x has an upper bound of 124 or less. |
当然,在这个特殊的例子中,你可以让你的生活更简单。
1 | return random.choice(('E', 'M', 'P', 'L', 'N')) |
简化了对更干净代码的链接调用。见下文
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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 |