查找CSV文件中的最大值 [英] Finding Maximum Value in CSV File

查看:312
本文介绍了查找CSV文件中的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有文件查找平均降雨量和最大降雨量的作业 BoulderWeatherData.csv 。已使用此代码找到平均值:

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

    rain = open("BoulderWeatherData.csv", "r")
    data = rain.readline()
    print(rain)
    data = rain.readlines()
    total = 0
    linecounter = 0
    for rain in data:
        linecounter = linecounter + 1
        print("The number of lines is", linecounter)

    for line in data:
        r = line.split(",")
        total = total + float(r[4])
    print(total)


    average = float(total / linecounter)
    print("The average rainfall is ", "%.2f" % average)

使用这个相同的过程找到最大。尝试使用 max 函数,但必须获得的答案是浮点数,不能通过 max 迭代。

However, can't seem to find maximum using this same process. Attempted using max, function but the answer that must be obtained is float number, which can not be iterated through max.

任何帮助将不胜感激。

Any help would be appreciated.

推荐答案

这是我最喜欢的处理方式。

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)

这将输出:

Average: 0.05465272591486193
Maximum: 1.98

这篇关于查找CSV文件中的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆