[英]sum the decimal number in list. python
我試圖打印訓練結果,但是無法總結測試精度。
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])
請記住, float 容易出現舍入錯誤,據我所知,您可以通過以下方式獲得額外的精度:
from decimal import Decimal
my_sum = sum(map(Decimal, q))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.