查找文本文件的最小值、最大值和平均值 [英] Find minimum, maximum, and average value of a text file

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

问题描述

我一直在拼命地为一个班级寻找这个问题的答案,但我似乎找不到.我需要从文本文件中收到的给定值中找到最小值、最大值和平均值.这就是我现在所拥有的.甚至没有打印任何东西,我也没有收到任何错误.我将根据我教授给我们的大纲进行学习,但仍有一些内容没有意义.

i've been desperately trying to find an answer to this for a class, and I cannot seem to find one. I need to find the minimum, maximum, and average value from given values received from a text file. Here's what I have right now. Nothing even prints and I'm not getting any errors. I'm going based off of an outline that my professor gave us, but still some of the stuff isn't making sense.

#2
inputFilename=input("Enter the filename: ")
inputFile=open(inputFilename, "r")
for item in inputFile:
    print(item.rstrip())
#3
item=inputFile.readline()
data=item.rstrip()
smallest, largest, sum=data, data, data
count=1
for item in inputFile:
    data=int(item.rstrip())
    if data<=item.strip():
        largest=data
    if data>=item.strip():
        smallest=data
    sum=
    count=count+1
print("smallest: ", smallest, "largest: ",largest, "average: ")
inputFile.close()

推荐答案

假设您的输入文件是由换行符分隔的整数,这里有两种方法.

Assuming your input file is integers separated by newlines, here are two approaches.

方法一:将所有元素读入一个列表,对列表进行操作

Approach 1: Read all elements into a list, operate on the list

# Open file, read lines, parse each as an integer and append to vals list
vals = []
with open('input.txt') as f:
    for line in f:
        vals.append(int(line.strip()))

print(vals)     # Just to ensure it worked

# Create an average function (much more verbose than necessary)
def avg(lst):
    n = sum(lst)
    d = len(lst)
    return float(n)/d

# Print output
print("Min: %s" % min(vals))    # Min: 1
print("Max: %s" % max(vals))    # Max: 10
print("Avg: %s" % avg(vals))    # Avg: 5.5

方法 2: 一次读取一个元素,为每个元素维护 min/max/sum/count:

Approach 2: Read one element at a time, maintain min/max/sum/count for each element:

_min = None
_max = None
_sum = 0
_len = 0
with open('input.txt') as f:
    for line in f:
        val = int(line.strip())
        if _min is None or val < _min:
            _min = val
        if _max is None or val > _max:
            _max = val
        _sum += val
        _len += 1

_avg = float(_sum) / _len

# Print output
print("Min: %s" % _min)     # Min: 1
print("Max: %s" % _max)     # Max: 10
print("Avg: %s" % _avg)     # Avg: 5.5

(输入文件只是整数 1-10,以换行符分隔)

(The input file was just the integers 1-10, separated by newlines)

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

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