我有以下功能,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
答案 0 :(得分:1)
@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'))
答案 1 :(得分:0)
简化的链式调用需要更简洁的代码。见下文
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