我正在尝试打印训练结果,但无法汇总测试的准确性。
q=(['0.50000', '0.56250', '0.50000', '0.50000'])
sum(q)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
您有一个str
的列表,因此首先必须将它们转换为float
,这可以使用sum
中的生成器表达式来完成。
>>> sum(float(i) for i in q)
2.0625
应该有人发布imho的正确版本(请参阅下面的评论(:
>>> sum(map(float, q))
2.0625
sum
函数使用起始值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.
因此,添加一个带有字符串对象的int对象将引发TypeError
>>> 0 + '0.50000'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
为了解决此问题,可以先将字符串对象转换为浮点对象,然后应用sum
函数。
您可以这样做:
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)
或
q=(['0.50000', '0.56250', '0.50000', '0.50000'])
sum([float(x) for x in q])