簡體   English   中英

使用 itertools.accumulate 函數時舍入列表中的值

[英]Rounding values in list when using itertools.accumulate function

我有一個四舍五入到十分之一的數字列表:

myList =
[2.3,
 14.4,
 21.6,
 6.0,
 2.6,
 4.2,
 7.6,
 46.7,
 8.1,
 1.2,
 7.6,
 6.2,
 8.3,
 17.7,
 27.3,
 5.4,
 18.6,
 6.4,
 6.4,
 40.4,
 28.4,
 36.0,
 21.5,
 4.7,
 19.6,
 22.0,
 18.2,
 19.9,
 12.1,
 20.7,
 1.0,
 11.8,
 1.1,
 3.2,
 8.0,
 6.5,
 4.3,
 6.4,
 4.3,
 16.7,
 17.8,
 2.7,
 7.5,
 1.5,
 2.5,
 7.8,
 4.4,
 10.2,
 14.8,
 25.1]

當我將此列表輸入itertools.accumulate函數並生成一個新列表(即運行總數)時,由於浮點運算,某些值有幾個小數位。

from itertools import accumulate

accumulated_list = list(accumulate(myList))
accumulated_list

輸出到:

[2.3,
 16.7,
 38.3,
 44.3,
 46.9,
 51.1,
 58.7,
 105.4,
 113.5,
 114.7,
 122.3,
 128.5,
 136.8,
 154.5,
 181.8,
 187.20000000000002,
 205.8,
 212.20000000000002,
 218.60000000000002,
 259.0,
 287.4,
 323.4,
 344.9,
 349.59999999999997,
 369.2,
 391.2,
 409.4,
 429.29999999999995,
 441.4,
 462.09999999999997,
 463.09999999999997,
 474.9,
 476.0,
 479.2,
 487.2,
 493.7,
 498.0,
 504.4,
 508.7,
 525.4,
 543.1999999999999,
 545.9,
 553.4,
 554.9,
 557.4,
 565.1999999999999,
 569.5999999999999,
 579.8,
 594.5999999999999,
 619.6999999999999]

我參考了一些主要的帖子和教程,但無法修復我的accumulated_list
將浮點數限制為兩位小數
https://docs.python.org/3/tutorial/floatingpoint.html

如何將這些解析為再次四舍五入到十分之一的數字? (不是格式化打印,而是四舍五入值。)

我試過使用
list(numpy.round(accumulate(myList),1))或使用decimal模塊將數字設置為decimal但無濟於事。
list(accumulate(myList.quantize(Decimal('0.1'))))

添加有關將元素實現為十進制的更多信息。 上面的myList是從一個函數生成的。 如何將元素實現為decimal

import numpy as np

def simulate(mean, size):
    return list(np.round(np.random.exponential(mean, size), 1))

myList = simulate(15, 50)

你可以這樣做:

import numpy as np
accumulated_list = np.around(np.cumsum(myList), decimals=1)

謝謝

您可以簡單地將它們round到一位小數:

accumulated_list = list(map(lambda x: round(x, 1), accumulate(myList)))

您可以使用round函數對結果進行round 使用maplambda功能,通過產生每一個項目做accumulate

accumulated = map(lambda x: round(x, 1), accumulate(myList))
print(list(accumulated))

# outputs the following list
[2.3, 16.7, 38.3, 44.3, 46.9, 51.1, 58.7, 105.4, 113.5, 114.7, 122.3, 128.5, 136.8, 154.5, 181.8, 187.2, 205.8, 212.2, 218.6, 259.0, 287.4, 323.4, 344.9, 349.6, 369.2, 391.2, 409.4, 429.3, 441.4, 462.1, 463.1, 474.9, 476.0, 479.2, 487.2, 493.7, 498.0, 504.4, 508.7, 525.4, 543.2, 545.9, 553.4, 554.9, 557.4, 565.2, 569.6, 579.8, 594.6, 619.7]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM