【发布时间】:2015-10-17 08:08:02
【问题描述】:
我有一个包含如下数字的文本文件:
a: 0.8475
b: 0.6178
c: 0.6961
d: 0.7565
e: 0.7626
f: 0.7556
g: 0.7605
h: 0.6932
i: 0.7558
j: 0.6526
我只想从此文件中提取浮点数并计算平均值。到目前为止,这是我的程序,
fh = file.open('abc.txt')
for line in fh:
line_pos = line.find(':')
line = line[line_pos+1:]
line = line.rstrip()
sum = 0
average = 0
for ln in line:
sum = sum + ln
average = sum / len(line)
print average
谁能告诉我,这段代码有什么问题。谢谢
【问题讨论】:
-
请注意,骗子只处理整数,所以要小心!
-
use
math.fsum()to avoid loosing precision。考虑sum([1e20, 1, -1e20]) == 0.0与math.fsum([1e20,1,-1e20]) == 1.0。L = [float(line.split(':')[1]) for line in open('abc.txt')]; average = math.fsum(L) / len(L)
标签: python