如何在.txt文件中查找平均值 [英] How to find the average of values in a .txt file

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

问题描述

我需要找到.txt文件中给出的最小值,最大值和平均值.我已经能够找到最小值和最大值,但是我一直在努力寻找平均值.我没有编写任何代码来确定平均值,因为我不知道从哪里开始.我当前的代码是:

I need to find the minimum, maximum, and average of values given in a .txt file. I've been able to find the minimum and maximum values but I'm struggling with finding the average of values. I haven't wrote any coding for determining the average as I have no clue where to start. My current code is:

def summaryStats():
    filename = input("Enter a file name: ")
    file = open(filename)
    data = file.readlines()
    data = data[0:]
    print("The minimum value is " + min(data))
    print("The maximum value is " + max(data))

我需要能够返回这些值的平均值.到目前为止,.txt文档具有以下值:

I need to be able to return the average of these values. As of now the .txt document has the following values:

893
255
504

我一直在努力寻找这些平均值,因为我试图找到总和的所有方法都是0.

I'm struggling on being able to find the average of these because every way I try to find the sum my result is 0.

谢谢 (对不起,我只是在学习使用文件)

Thanks (sorry I'm just learning to work with files)

推荐答案

您应该首先将从文件中检索的数据转换为整数,因为数据列表包含的字符串不是数字.在转换为整数后,可以很容易地找到平均值:

You should convert the data retrived from file to integers first, because your data list contains strings not numbers. And after the conversion to integers average can be found easily:

为什么需要转换为int?

Why conversion to int is required?

>>> '2' > '10'  #strings are compared lexicographically
True

代码:

def summaryStats():
    filename = input("Enter a file name: ")
    with open(filename) as f:
        data = [int(line) for line in f]

    print("The minimum value is ", min(data))
    print("The maximum value is ", max(data))
    print("The average value is ", sum(data)/len(data))

输出:

Enter a file name: abc1
The minimum value is  255
The maximum value is  893
The average value is  550.6666666666666

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

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