简体   繁体   English

总结列表中的十进制数。 Python

[英]sum the decimal number in list. python

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 .您有一个str列表,因此首先您必须将它们转换为float ,您可以使用sum的生成器表达式来完成。

>>> sum(float(i) for i in q)
2.0625

Someone should post the imho proper version (see comments below):有人应该发布 imho 正确版本(见下面的评论):

>>> sum(map(float, q))
2.0625

sum function uses start value 0 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.

So adding a int object with a string object will raise TypeError所以添加一个带有字符串对象的 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'

In order to fix this you can convert the string object into float object first and then apply the sum function.为了解决这个问题,您可以先将字符串对象转换为浮点对象,然后再应用sum函数。

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])

Remember that float are prone to rounding errors, to my understanding you can get a little extra precision with:请记住, float 容易出现舍入错误,据我所知,您可以通过以下方式获得额外的精度:

from decimal import Decimal
my_sum = sum(map(Decimal, q))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM