I have the list of [0.5, 1.5, 2.5, 3.5].
JavaScript
x
5
1
def calc_mean(arglist):
2
return sum(arglist)/len(arglist)
3
4
print(calc_mean([0.5, 1.5, 2.5, 3.5]))
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]
JavaScript
1
8
1
def str2float(strlist):
2
flist = [float(i) if '.' in i else int(i) for i in strlist]
3
return flist
4
5
strlist = ['0.5','1.5','2.5','3.5']
6
print(str2float(strlist))
7
print(calc_mean(strlist))
8
Advertisement
Answer
JavaScript121print(calc_mean(strlist))
2
As noted in comments, you have not converted strlist
before passing it to calc_mean
.
JavaScript
1
2
1
print(calc_mean(str2float(strlist)))
2