当我比较温度来确定温度的形容词时,我得到了很多丑陋的if elif's,我想我可以在字典的列表中查找温度值,其中的键将是对应的温度形容词:
def确定最低温度(温度):
temps = {
'FREEZING' : [i for i in range(-20, 0)],
'very cold' : [i for i in range(0, 6)],
'cold' : [i for i in range(6, 11)],
'chilly' : [i for i in range(11, 16)],
'cool' : [i for i in range(16, 21)],
'warm' : [i for i in range(21, 26)],
'hot' : [i for i in range(26, 31)],
'very hot' : [i for i in range(31, 36)],
'dangerously hot' : [i for i in range(36, 40)],
'extremely dangerously hot': [i for i in range(41, 46)]
}
temp = int(temp.replace('°', '').strip())
for word, values in temps.items():
if temp in values:
return word
如果是elif,这比7+要好得多,但我认为这不是很有效,特别是如果temps有更多的数据(例如,如果我有一个与形容词对应的较窄的值范围)
有什么方法可以提高效率?也许字典里有些功能?以上是我能想到的最好的
This与我所寻找的最接近
输出:
您需要以某种方式存储范围,并且由于范围没有相同的间隔,因此无法真正缩短字典初始化。您可以将字典创建提取到一个函数中,但是您仍然需要根据您的选项多次调用它
但是,您可以从字典中删除列表理解,并将循环替换为
next
如果您决定将温度表示为浮点数,则代码通常无法工作。为确保代码适用于非整数温度(以防万一),请将范围表示为最小-最大值对,并使用显式比较:
您也可以使用元组列表,因为您不使用特定于词典的功能:
最后,为了保持一致性,您可以只定义范围上限边界(同时也是下一个范围的下限边界):
相关问题 更多 >
编程相关推荐