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

时间:2015-03-15 21:07:28

标签: python text

我一直拼命想为一个班级找到答案,我似乎找不到一个。我需要从文本文件中收到的给定值中找到最小值,最大值和平均值。这就是我现在所拥有的。什么都打印,我没有任何错误。我的目的是基于我的教授给我们的大纲,但仍有一些东西没有意义。

#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()

1 个答案:

答案 0 :(得分:3)

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

方法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

方法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

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