简体   繁体   中英

average computing without using sum function in python?

I'm trying to solve a python code for reading a text file then select some similar text, then collect the float numbers from them and count their average, without using the SUM function .

but I have a column of list of the average of each number with its before numbers! and the last one is my answer but I cannot select the last character as the python looks at it as one columnar strange number!

this is my code :

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

the answer:

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)

You are printing the average calculated so far each time you find a matching line.

This is why you get the running average; for the first line, there is only one value, so the average of one value is that value. You print again when you updated the average for the second line, etc.

You only need to calculate the average when you have collected the total for all lines. When iterating over the file, you only need to count the number of matching lines and update the total value.

Put your average calculation outside the for loop. Take into account there could be 0 matching lines:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM