我需要找出一系列数字的相对频率。我几乎已经完成但是我需要将给定的数字四舍五入到这样的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]
我试过了:
total = float(sum(counts))
freq = []
for count in counts:
freq.append(float(count/total))
return(freq)
出来了:
counts2frequencies([8,2,3,10,5])
Out[51]:
[0.2857142857142857,
0.07142857142857142,
0.10714285714285714,
0.35714285714285715,
0.17857142857142858]
如何舍入列表中的数字?函数round()
不能以某种方式工作。
答案 0 :(得分:1)
舍入到小数点后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)
对其进行舍入:
>>> print('{:.08f}'.format(0.07142857142857142))
0.07142857
>>> print('{:.08f}'.format(0.07))
0.07000000