Python中的百分比和舍入

时间:2011-11-02 18:09:44

标签: python rounding

我有一个代码,用于创建文本文件中某些字长的百分比丰度列表,例如1个字母的单词出现在13%的时间,我想知道的是,如果在50,000个单词的文本文件中有1个20个字母的单词,它会将20个字母单词的百分比四舍五入到0或最多1个吗?

这是整个代码:

lines = open ('E:\Videos, TV etc\Python\Assessment\dracula.txt', 'r'). readlines ()

stripped_list = [item.strip() for item in lines]

tally = [0] * 20

print tally #original tally

for i in stripped_list:
    length_word = int(len(i))
    tally[length_word-1] += 1 #adds 1 to the tally for the index of that word length, (length_word)-1 used as the tally for 1 letter words are in the 0 index
print tally

new_tally = [] #this tally will contain the occurences of each word length by percentage
for a in tally:
    new_tally.append((100*a)/(sum(tally))) # multiplies by 100 and divides by all of the tallies to give a percentage
print new_tally

4 个答案:

答案 0 :(得分:3)

默认情况下,如果分子和分母都是整数,则会截断数字。

>>> 1 / 50000
0

要解决和实际百分比,您可以将值中的一个或两个更改为浮点数

>>> 1.0 / 50000
2e-05

如果你在谈论变量,

>>> cnt, all = 1, 50000
>>> float(cnt) / all
2e-05

乘以100得到百分比。

答案 1 :(得分:2)

假设您使用的是int(),那么Python 总是向下舍入。 int(0.99999)= 0.它实际上只是丢弃小数后的部分。

如果你想要更像大多数人所说的四舍五入的东西,你可以这样做:    “%0.0f”%(yourval,)。

那使用了一个算法,其名称逃脱了我,其中数字正好在中间的圆形朝向最近的偶数数字,所以0.5变为0,但1.5变为2. 0.49总是0, 0.51始终为1.

答案 2 :(得分:2)

它会将答案缩小到0。

答案 3 :(得分:2)

您的代码使用的是整数分区,它始终向零舍入。

通过使用浮点除法和Python的round()内置函数来获得更多控制:

percentage = round((100.0*a) / sum(tally))
相关问题