【问题标题】:Calculating average of the numbers in a .txt file using Python [duplicate]使用Python计算.txt文件中数字的平均值[重复]
【发布时间】: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.0L = [float(line.split(':')[1]) for line in open('abc.txt')]; average = math.fsum(L) / len(L)

标签: python


【解决方案1】:

您在错误的位置添加了sum,并且您需要跟踪行数,因为您无法将文件对象发送到len()。您还必须将字符串转换为floats。我也建议简单地分割空白。最后,使用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

【讨论】:

  • 这只是因为分隔符是: 而起作用(注意尾随空格。可能更安全的是line.split(":")
  • 我不确定冒号或空格是否是其中更可靠的部分,所以我只是假设它们都同样有效。如果可以选择,空格split 看起来更干净一些,所以我选择了它。但是是的,如果事实证明空格是任意的,而冒号不是,那么就需要进行更改。
【解决方案2】:
  • 将该行转换为float 以进行数字加法。
  • 初始化一次sum(在循环开始之前)。计算一次循环后的平均值。
  • len(line) 会给你错误的号码。最后一个数字的数字 + 换行字符数。
  • 尽量避免使用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

【讨论】:

  • 这可能有效,但在 Python 中非常不习惯。尽量避免使用str.find 命令。在这种情况下num = float(line.split(":"))[-1] 就足够了
  • @AdamSmith,感谢您的评论。我相应地更新了答案。
猜你喜欢
  • 1970-01-01
  • 2021-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-11
  • 2016-05-22
  • 1970-01-01
  • 2014-04-20
相关资源
最近更新 更多