i wass trying to print the Training result, However, the test accuracy can not be sumed.
q=(['0.50000', '0.56250', '0.50000', '0.50000'])
sum(q)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
i wass trying to print the Training result, However, the test accuracy can not be sumed.
q=(['0.50000', '0.56250', '0.50000', '0.50000'])
sum(q)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
You have a list of str
so first you have to convert them to float
, which you can do using a generator expression within sum
.
>>> sum(float(i) for i in q)
2.0625
Someone should post the imho proper version (see comments below):
>>> sum(map(float, q))
2.0625
sum
function uses start value 0
>>> help(sum)
Help on built-in function sum in module builtins:
sum(iterable, /, start=0)
Return the sum of a 'start' value (default: 0) plus an iterable of numbers
When the iterable is empty, return the start value.
This function is intended specifically for use with numeric values and may
reject non-numeric types.
So adding a int object with a string object will raise TypeError
>>> 0 + '0.50000'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
In order to fix this you can convert the string object into float object first and then apply the sum
function.
you can do it like this:
q=(['0.50000', '0.56250', '0.50000', '0.50000'])
result = 0 # create a variable wich will store the value.
for i in q: # loop over your elements
result += float(i) # cast your temp variable (i) to float and add each element to result.
print(result) # escape the loop and print the result variable.
q=([0.50000, 0.56250, 0.50000, 0.50000])
sum(q)
or
q=(['0.50000', '0.56250', '0.50000', '0.50000'])
sum([float(x) for x in q])