在.txt文件python中查找平均值

时间:2014-03-14 16:16:29

标签: python text max average minimum

我需要从.txt文件中打印出平均高度。我该如何轻松地编写它? .txt文件包含以下数字:

12
14
59
48
45
12
47
65
152

这是我到目前为止所得到的:

import math

text = open(r'stuff.txt').read()
data = []
with open(r'stuff.txt') as f:
    for line in f:
        fields = line.split()
        rowdata = map(float, fields)
        data.extend(rowdata)

biggest = min(data)
smallest = max(data)
print(biggest - smallest)

6 个答案:

答案 0 :(得分:1)

要计算某些数字的平均值,您应该将它们相加,然后除以数字的数量:

data = []
with open(r'stuff.txt') as f:
    for line in f:
        fields = line.split()
        rowdata = map(float, fields)
        data.extend(rowdata)

print(sum(data)/len(data))

答案 1 :(得分:1)

data = [float(ln.rstrip()) for ln in f.readlines()]  # Within 'with' statement.
mean_average = float(sum(data))/len(data) if len(data) > 0 else float('nan')

这是计算平均值平均值的方法,如果这是你的意思。遗憾的是,math没有这方面的功能。仅供参考,我们会修改mean_average行,以避免ZeroDivisionError长度为list时出现的0错误 - 以防万一。

答案 2 :(得分:1)

# import math -- you don't need this

# text = open(r'stuff.txt').read() not needed.
# data = [] not needed

with open(r'stuff.txt') as f:
    data = [float(line.rstrip()) for line in f]

biggest = min(data)
smallest = max(data)
print(biggest - smallest)
print(sum(data)/len(data))

答案 3 :(得分:0)

数组平均值可以这样计算:

print(sum(data) / len(data))

答案 4 :(得分:0)

用于查找平均值的简单程序如下(如果我理解的话,你的文件在每一行中都有一个值,如果是这样,它必须与此类似,否则它必须相应地改变):

import sys

f = open('stuff.txt', 'rU')    
lines = f.readlines()    
f.close()

size =  len(lines)
sum=0
for line in lines:
    sum = sum + float(line.rstrip())

avg = sum / float(size)    
print avg,

不是python中最好的,但我认为这很直接......

答案 5 :(得分:0)

一个完整的,几乎没有循环的解决方案,结合了这里其他答案的要素:

with open('stuff.txt','r') as f:
    data = [float(line.rstrip()) for line in f.readlines()]
    f.close()
mean = float(sum(data))/len(data) if len(data) > 0 else float('nan')

,您无需添加,添加,封装或导入其他任何内容。