Home > Enterprise >  Finding average of the numbers in each line Python
Finding average of the numbers in each line Python

Time:07-02

I have a program which grabs the drivers laptimes and writes them to a txt file. output.txt looks like this:

 33.818
 33.636
 33.843
 33.909

I want to sum all the lap times and divide it by lap count(basically find the average of them). But i cant manage to sum them correctly. How can i do it?

CodePudding user response:

file = open("output.txt", "r")
line = file.readline() # I assume this is to ignore the first line
count = 0
total = 0
for line in open('output.txt'): 
    total  = float(line.strip())
    count  = 1
average = total/count
print(average)

CodePudding user response:

You can use timedelta

import datetime as dt

def avg_time(lst:list):
    n=len(lst)
    res=[]
    for i in lst:
        hour,minute,second=i.split(":")
        second,milli=second.split(".")
        res.append(dt.timedelta(hours=int(hour),minutes=int(minute),seconds=int(second),milliseconds=int(milli)))
    return sum(res,dt.timedelta(0))/n


t = ["00:01:26.102","00:01:15.618","00:01:15.096","00:01:14.792","00:01:14.532","00:01:25.083","00:01:25.497","00:01:17.809","00:01:19.364",
"00:01:18.935","00:01:18.076","00:01:18.111","00:01:22.086","00:01:20.500","00:01:18.167","00:01:18.268","00:01:18.373","00:01:17.950","00:01:17.944",]

a = avg_time(t)
print(a) # to get same format of timedelta as print convert it to str

Output:

0:01:19.068579

PS. you can not format timedelta like other datetime object. So you can use some normal Maths to get it as follows:

total_second=a.total_seconds()
hour_s,second_s=divmod(total_second,3600)
minute_s,second_s=divmod(second_s,60)

According yo requirement do some modification for time unit i.e. hour, minute, seconds which are required or not required.

  • Related