我已经创建了一个程序,可以定义12个月的最高、最低和平均温度,但我想通过寻找平均温度最热和最冷的月份来扩展它。我当前的代码是:
def main():
months = [ ["January", 6,3],
["February", 7,3],
["March", 10,4],
["April", 13,6],
["May", 17,9],
["June", 20,12],
["July", 22,14],
["August", 21,14],
["September",19,12],
["October", 14,9],
["November", 10,6],
["December", 7,3] ]
for month in months:
month_name = month[0]
temp = month[1:]
minTemp = min(temp)
avgTemp = sum(temp)/len(temp)
maxTemp = max(temp)
print (month_name, minTemp, avgTemp, maxTemp)
main()我想添加类似这样的内容:“如果month_name具有最高平均温度,则打印month_name及其温度。如果month_name具有最低平均温度,则打印month_name及其温度。
发布于 2020-11-30 00:49:08
import math
def main():
months = [ ["January", 6,3],
["February", 7,3],
["March", 10,4],
["April", 13,6],
["May", 17,9],
["June", 20,12],
["July", 22,14],
["August", 21,14],
["September",19,12],
["October", 14,9],
["November", 10,6],
["December", 7,3] ]
mn,mx=math.inf, -math.inf
mx_month=["",0]
mn_month=["",0]
for month in months:
month_name = month[0]
temp = month[1:]
minTemp = min(temp)
avgTemp = sum(temp)/len(temp)
maxTemp = max(temp)
if avgTemp<mn:
mn_month[0],mn_month[1]=month_name,avgTemp
mn=avgTemp
if avgTemp>mx:
mx_month[0],mx_month[1]=month_name,avgTemp
mx=avgTemp
print (month_name, minTemp, avgTemp, avgTemp)
print("Min avg temo month and temp: ",mn_month)
print("Max avg temo month and temp: ",mx_month)
main()发布于 2020-11-30 00:47:19
将每个月的平均值附加到最小值/最大值
months = [["January", 6, 3],
["February", 7, 3],
["March", 10, 4],
["April", 13, 6],
["May", 17, 9],
["June", 20, 12],
["July", 22, 14],
["August", 21, 14],
["September", 19, 12],
["October", 14, 9],
["November", 10, 6],
["December", 7, 3]]
for m in months:
m.append((m[1] + m[2]) / 2)
_min_avg = min(months, key = lambda k: k[3])
_max_avg = max(months, key = lambda k: k[3])
print(_min_avg)
print(_max_avg)https://stackoverflow.com/questions/65062457
复制相似问题