Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

python 3.x - How can I have the averageHighTemps function to take the weather database as an argument, and returns the average of the monthly high temperatures

def main():

    highTemps = [-3, -2, 3, 11, 19, 23, 26, 25, 20, 13, 6, 0]
    lowTemps = [-11, -10, -5, 1, 8, 13, 16, 15, 11, 5, -1, -7]
    weatherDB = createDB(highTemps, lowTemps)  


    for m in weatherDB: 
        for t in weatherDB[m]: 
            print(m, t, weatherDB[m][t])

    m = input("Enter a Month Name: ")
    if m in weatherDB: 
      print(weatherDB[m])
    else: 
      print("Month not found")

def tempByMonth(weatherDB, month):
    months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"]

    weatherDB = {}

    for i in range(len(months)):
      month = months[i]
      weatherDB[month]

    return weatherDB

def averageHighTemps(weatherDB):
#Here is the function
    return


#DO NOT change this function:
def createDB(highTemps, lowTemps):
    months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"]

    weatherDB = {}

    for i in range(len(months)):
        month = months[i]
        weatherDB[month]={"high":highTemps[i],"low":lowTemps[i]}

    return weatherDB


main()

How can I have the averageHighTemps function to take the weather database as an argument, and returns the average of the monthly high temperatures. This code should only be in the function of averageHighTemps.

question from:https://stackoverflow.com/questions/65833487/how-can-i-have-the-averagehightemps-function-to-take-the-weather-database-as-an

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm not entirely sure what you're after but this takes the weatherDB as an argument, creates a list of the high temperature from each month and from that calculates a mean average.

def averageHighTemps(weatherDB):
    highs = [month["high"] for month in weatherDB.values()]
    avg = sum(highs) / len(weatherDB)
    return avg

You would then probably want to put in your main() function:

print(f"The average high temperature was: {averageHighTemps(weatherDB)}")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...