J'ai créé un programme qui peut définir la température maximale, minimale et moyenne de 12 mois, mais je veux l'étendre en trouvant des mois avec la température moyenne la plus chaude et la plus froide. Mon code actuel est:

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()

Je veux ajouter quelque chose comme "si month_name a la température moyenne maximale, imprimez month_name et ses températures. Aussi si month_name a la température moyenne minimale, imprimez month_name et son les températures

0
Alexander Urum 29 nov. 2020 à 19:32

2 réponses

Meilleure réponse
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()
1
toRex 29 nov. 2020 à 17:19

Ajoutez la moyenne à chaque mois et trouvez min / max

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)
0
balderman 29 nov. 2020 à 16:47