我有一个包含如下数字的文本文件:
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
有谁能告诉我,这段代码有什么问题。感谢
答案 0 :(得分:2)
float
以进行数字添加。sum
一次(在循环开始之前)。计算循环一次后的平均值。str.find
+切片。使用str.split
更具可读性。with open('abc.txt') as fh:
sum = 0
numlines = 0
for line in fh:
n = line.split(':')[-1]
sum += float(n)
numlines += 1
average = sum / numlines
print average
答案 1 :(得分:2)
您在错误的位置添加了sum
,并且您需要跟踪行数,因为您无法将文件对象发送到len()
。您还必须将字符串强制转换为float
s。我也建议简单地拆分空格。最后,使用with
构造自动关闭文件:
with open('abc.txt') as fh:
sum = 0 # initialize here, outside the loop
count = 0 # and a line counter
for line in fh:
count += 1 # increment the counter
sum += float(line.split()[1]) # add here, not in a nested loop
average = sum / count
print average