I have the list of [0.5, 1.5, 2.5, 3.5].
def calc_mean(arglist): return sum(arglist)/len(arglist) print(calc_mean([0.5, 1.5, 2.5, 3.5]))
I have another list, strlist = ['0.5','1.5','2.5','3.5']
and I need to convert the elements in it to floats and then calculate the average but I’m getting the error:
unsupported operand type(s) for +: 'int' and 'str')
because the line return sum(arglist)/len(arglist) is working with integers and strlist is a string why strlist isn’t being converted to a float and it’s being treated as a str even though I converted it using [float(i) if ‘.’ in i else int(i) for i in strlist]
def str2float(strlist): flist = [float(i) if '.' in i else int(i) for i in strlist] return flist strlist = ['0.5','1.5','2.5','3.5'] print(str2float(strlist)) print(calc_mean(strlist))
Advertisement
Answer
print(calc_mean(strlist))
As noted in comments, you have not converted strlist
before passing it to calc_mean
.
print(calc_mean(str2float(strlist)))