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

时间:2016-05-02 08:34:16

标签: python average

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

但我有一列列表,其中包含每个号码的平均值以及之前的数字!最后一个是我的答案,但我无法选择最后一个字符,因为python将其视为一个柱状奇怪数字!

这是我的代码:

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

答案 0 :(得分:0)

每次找到匹配的行时,您都会打印到目前为止计算的平均

这就是为什么你得到了平均值;对于第一行,只有一个值,因此一个值的平均值就是该值。更新第二行的平均值时再次打印

您只需计算收集所有行总数的平均值。迭代文件时,只需计算匹配行数并更新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