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

12
14
59
48
45
12
47
65
152

import math

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 个答案:

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

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')

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

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

import sys

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

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

avg = sum / float(size)
print avg,

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')

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