简体   繁体   English

查找文本文件的最小值,最大值和平均值

[英]Find minimum, maximum, and average value of a text file

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 方法1 :将所有元素读入列表,在列表上进行操作

# 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

Approach 2: Read one element at a time, maintain min/max/sum/count for each element: 方法2:一次读取一个元素,并为每个元素保持最小/最大/总和/计数:

_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

(The input file was just the integers 1-10, separated by newlines) (输入文件只是整数1-10,用换行符分隔)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM