数字列表的相对频率

2024-10-01 22:41:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要找出一组数字的相对频率。我快完成了,但我需要将给定的数字四舍五入到8位,如下所示:

def counts2frequencies(counts):

       freq = counts2frequencies(counts)
    Input argument:
       counts: list with numbers
    Output argument:
       freq: list with frequencies
    Example: 
       counts2frequencies([8,2,3,10,5])
       =>
       [0.28571429, 0.07142857, 0.10714286, 0.35714286, 0.17857143]

我试过了:

^{pr2}$

结果是:

counts2frequencies([8,2,3,10,5])

Out[51]: 
[0.2857142857142857,
0.07142857142857142,
0.10714285714285714,
0.35714285714285715,
0.17857142857142858]

我怎样把名单上的数字四舍五入?函数round()以某种方式不起作用。在


Tags: inputoutputexampledefwith数字argumentlist
1条回答
网友
1楼 · 发布于 2024-10-01 22:41:16

四舍五入到小数点后8位:

>>> l
[0.2857142857142857, 0.07142857142857142, 0.10714285714285714,
 0.35714285714285715, 0.17857142857142858]
>>> lrounded = [ round(i, 8) for i in l ]
[0.28571429, 0.07142857, 0.10714286, 0.35714286, 0.17857143]

但是,右边的方法是在打印时取整它们,使用'{:.08f}'.format(i)

^{pr2}$

相关问题 更多 >

    热门问题