Python中的百分比和四舍五入
我有一段代码,它可以生成一个列表,显示某些字母长度的单词在一个文本文件中出现的百分比。例如,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 个回答
2
假设你在使用int()这个函数,那么在Python中,总是向下取整。比如int(0.99999)的结果是0。其实就是把小数点后面的部分直接去掉了。
如果你想要的结果更像大多数人理解的四舍五入,可以这样做: "%0.0f" % (yourval,)。
这个方法使用了一种算法,名字我记不太清了。它的规则是,如果数字正好在中间,就会向最近的偶数取整,所以0.5会变成0,而1.5会变成2。0.49总是变成0,0.51总是变成1。
3
默认情况下,如果分子和分母都是整数,你得到的结果会是一个截断的数字。
>>> 1 / 50000
0
为了得到真实的百分比,你可以把其中一个或两个数值改成浮点数。
>>> 1.0 / 50000
2e-05
如果你在讨论变量的话,
>>> cnt, all = 1, 50000
>>> float(cnt) / all
2e-05
可以把结果乘以100来得到百分比。
3
你的代码正在使用整数的向下取整除法,这种方法总是向零的方向取整。
如果想要更灵活的控制,可以使用浮点数除法,并结合Python的 round() 内置函数:
percentage = round((100.0*a) / sum(tally))