Finding Maximum Value in CSV File

后端 未结 5 2014
醉梦人生
醉梦人生 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 07:08

    This code will attempt to find the maximum value, and the average value, of floats stored in the 5th position in a .csv.

    rainval = []
    

    Initializes the empty array where we will store values.

    with open ("BoulderWeatherData.csv", "r") as rain:
    

    Opens the .csv file and names it "rain".

        for lines in rain:
    

    This reads every line in rain until the end of the file.

            rainval += [float(lines.strip().split(",")[4])]
    

    We append the float value found in the fifth position (fourth index) of the line.

    We repeat the above for every line located in the .csv file.

    print (sorted(rainval)[len(rainval)])
    

    This sorts the values in the rainval array and then takes the last (greatest) value, and prints it. This is the maximum value and is better than max because it can handle floats and not just ints.

    print (sum(rainval)/len(rainval))
    

    This prints the average rainfall.


    Alternatively, if we don't want to use arrays:

    maxrain = -float("inf")
    total, count = 0, 0
    with open ("test.txt", "r") as rain:
        for lines in rain:
            temp = float(lines.strip().split(",")[4])
            if maxrain < temp:
                maxrain = temp
            total += temp
            count += 1
    
    print (maxrain)
    print (total/count)
    

提交回复
热议问题