代码之家  ›  专栏  ›  技术社区  ›  Farbod

在python中不使用sum函数的平均计算?

  •  0
  • Farbod  · 技术社区  · 10 年前

    我正在尝试解出一个用于读取文本文件的python代码,然后选择一些类似的文本,然后从中收集浮点数并计算其平均值, 不使用SUM功能 .

    但我有一列列表,列出了每个数字的平均值及其前面的数字!最后一个是我的答案,但我无法选择最后一个字符,因为蟒蛇将其视为一列奇怪的数字!

    这是我的代码:

    count = 0
    total = 0
    
    while True:   
        inp = raw_input ("Enter file name: ")
        if inp == 'myfile.txt' : break
    
    fh = open(inp)
    for line in fh:
        line = line.rstrip()
        if line.startswith("my_pattern") :
            count = count + 1
            sb = line.split()
            sc = sb[1]    # this gaves me the numbers only from eavh line #
            value = float(sc)
    
            total = total + value
            average = total/count
            print average
    

    答案是:

    0.8475     (*this is exactly the first number, I mean it is the average of just one number, Itself !*)
    0.73265     (*this is the average of two numbers, the second number and the number 0.8475*)
    0.728447368421
    0.727035
    0.728385714286
    0.726895454545
    0.725547826087
    0.7268
    0.737112     (this is the answer, but I do not want a column of numbers and by the way, I could not split just this number)
    
    1 回复  |  直到 10 年前
        1
  •  0
  •   Martijn Pieters    10 年前

    您正在打印计算的平均值 目前为止 每次你找到一条匹配的线。

    这就是你获得跑步平均值的原因;对于第一行,只有一个值,所以一个值的平均值就是这个值。当更新第二行的平均值时,再次打印,依此类推。

    您只需要在收集以下项目的合计时计算平均值 全部的 线在遍历文件时,只需计算匹配行的数量并更新 total 价值

    把你的平均计算 外部 这个 for 环考虑到可能有0条匹配行:

    for line in fh:
        line = line.rstrip()
        if line.startswith("my_pattern") :
            count = count + 1
            sb = line.split()
            sc = sb[1]    # this gaves me the numbers only from eavh line #
            value = float(sc)
            total = total + value
    
    if count:
        average = total / count
        print average