Python无法使用“round”或“format”方法获得2位小数

2024-09-26 18:03:22 发布

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

我尝试了不同的方法来让它工作,但是它并没有像预期的那样改变值

for i in Lev1_clean_text:
    l = word_tokenize(i)
    c = Counter(category for token in l for category in parse(token))
    key_percent = [(i, round(c[i], 2) / len(l) * 100) for i in c]
    print(key_percent)

我也试着改变下面这行,但仍然没有给我想要的效果

key_percent = [(i, int('{:2}'.format(c[i])) / len(l) * 100) for i in c]

预期效果:

[('Hedge', 19.23), ('Absolute', 7.69)]
[('Negative', 12.5), ('Curses', 12.50), ('Hedge', 12.50), ('Absolute', 8.33)]

这就是我得到的:

[('Hedge', 19.230769230769234), ('Absolute', 7.6923076923076925)]
[('Negative', 12.5), ('Curses', 12.5), ('Hedge', 12.5), ('Absolute', 8.333333333333332)]

Tags: 方法keyincleantokenforlencurses
2条回答

假设c[i]123.45123len(l)1234

圆形(c[i],2)123.45

因此round(c[i],2)/len(l)123.45/1234,结果是0.10004051863857374

很明显你的表情是错的

正确的表达是

round(c[i]/len(l)*100, 2)

您只需对c[i]进行四舍五入,而应该对最后的数字进行四舍五入:

round(c[i] / len(l) * 100, 2)

相关问题 更多 >

    热门问题