Python Forum

Full Version: how to get the highest monthly average temperature?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
my question here
Create a program that reads from a file to display city name and average temperature in Celsius

use !curl to download https://raw.githubusercontent.com/Micros...p_mean.csv as mean_temp.txt

1) open the file in 'r' mode
2) read the first line of text into a variable called: headings and print()
3) convert headings to a list using .split(',') which splits on each comma, print() the list
4) use a while loop to read the remaining lines from the file
5) assign remainging lines to a city_temp variable
6) convert the city_temp to a list using .split(',') for each .readline() in the loop
7) print each city & the highest monthly average temperature
8)close mean_temps

!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/world_temp_mean.csv -o mean_temp.txt
mean_file=open("mean_temp.txt","r")
headings=mean_file.readline().strip('\n')
print(headings)
heading=headings.split(",")
print(heading)
city_temp=""
city_temp2=[]
headings2=mean_file.readline()
while headings2:
    city_temp+=headings2
    city_temp2.append(headings2.split(","))
    headings2=mean_file.readline()
    
print(city_temp)
print(city_temp2)
for city in city_temp2:
    print(city[0])
Output:

city,country,month ave: highest high,month ave: lowest low
['city', 'country', 'month ave: highest high', 'month ave: lowest low']
Beijing,China,30.9,-8.4
Cairo,Egypt,34.7,1.2
London,UK,23.5,2.1
Nairobi,Kenya,26.3,10.5
New York City,USA,28.9,-2.8
Sydney,Australia,26.5,8.7
Tokyo,Japan,30.8,0.9

[['Beijing', 'China', '30.9', '-8.4\n'], ['Cairo', 'Egypt', '34.7', '1.2\n'], ['London', 'UK', '23.5', '2.1\n'], ['Nairobi', 'Kenya', '26.3', '10.5\n'], ['New York City', 'USA', '28.9', '-2.8\n'], ['Sydney', 'Australia', '26.5', '8.7\n'], ['Tokyo', 'Japan', '30.8', '0.9\n']]
Beijing
Cairo
London
Nairobi
New York City
Sydney
Tokyo

But how to get the highest monthly average temperature?
you have list of lists.
each city is list with 4 elements - city, country, highest high average, lowest low average.
you need just 1 and 3 element of each list
You should use the module csv:
import csv


with open('world_temp_mean.csv') as fd:
    reader = csv.reader(fd)
    head = next(reader)
    data = list(reader)
Now you have data, which is a list. Each element in the list is one row of the data.
You can do an inline sort of the list. If you want to have different sorted new lists, you should use the built-in function sorted().

from operator import itemgetter


# avg highest tmp is in index 2
# sort by index 2
data.sort(key=itemgetter(2), reverse=True)
# or with lambda
data.sort(key=lambda x: x[2], reverse=True)