Home > Net >  How to compute the average of a string of floats
How to compute the average of a string of floats

Time:11-29

temp = "75.1,77.7,83.2,82.5,81.0,79.5,85.7"

I am stuck in this assignment and unable to find a relevant answer to help.

I’ve used .split(",") and float() and I am still stuck here.

CodePudding user response:

temp = "75.1,77.7,83.2,82.5,81.0,79.5,85.7"

li = temp.split(",")

def avr(li):
    av = 0
    for i in li:
        av  = float(i)
    return av/len(li)

print(avr(li))

CodePudding user response:

You can use sum() to add the elements of a tuple of floats:

temp = "75.1,77.7,83.2,82.5,81.0,79.5,85.7"

def average (s_vals):
    vals = tuple ( float(v) for v in s_vals.split(",") )
    return sum(vals) / len(vals)

print (average(temp))

CodePudding user response:

Admittedly similar to the answer by @emacsdrivesmenuts (GMTA).

However, opting to use the efficient map function which should scale nicely for larger strings. This approach removes the for loop and explicit float() conversion of each value, and passes these operations to the lower-level (highly optimised) C implementation.

For example:

def mean(s):
    vals = tuple(map(float, s.split(',')))
    return sum(vals) / len(vals)

Example use:

temp = '75.1,77.7,83.2,82.5,81.0,79.5,85.7'

mean(temp)
>>> 80.67142857142858
  • Related