Finding Maximum Value in CSV File

后端 未结 5 2075
醉梦人生
醉梦人生 2021-01-29 06:14

Have an assignment of finding average and maximum rainfall in file \"BoulderWeatherData.csv\". Have found the average using this code:

    rain = open(\"BoulderW         


        
5条回答
  •  情书的邮戳
    2021-01-29 06:54

    This is my prefered way of handling this.

    #!/usr/bin/env python3
    
    rain = open("BoulderWeatherData.csv","r")
    
    average = 0.0
    total = 0
    maxt = 0.0
    
    for line in rain:
        try:
            p = float(line.split(",")[4])
            average += p
            total += 1
            maxt = max(maxt,p)
        except:
            pass
    
    average = average / float(total)
    
    print("Average:",average)
    print("Maximum:",maxt)
    

    This will output:

    Average: 0.05465272591486193
    Maximum: 1.98
    

提交回复
热议问题