Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的百分比和舍入_Python_Rounding - Fatal编程技术网

Python中的百分比和舍入

Python中的百分比和舍入,python,rounding,Python,Rounding,我有一个代码,可以创建文本文件中某些单词长度的百分比丰度列表,例如,13%的时间出现1个字母单词,我想知道的是,如果50000个单词的文本文件中有1个20个字母的单词,它会将20个字母单词的百分比四舍五入到0还是最多1 以下是完整的代码: lines = open ('E:\Videos, TV etc\Python\Assessment\dracula.txt', 'r'). readlines () stripped_list = [item.strip() for item in lin

我有一个代码,可以创建文本文件中某些单词长度的百分比丰度列表,例如,13%的时间出现1个字母单词,我想知道的是,如果50000个单词的文本文件中有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

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

>>> 1 / 50000
0
若要解决实际百分比和实际百分比的问题,请将其中一个或两个值更改为浮点数字

>>> 1.0 / 50000
2e-05
如果你说的是变量

>>> cnt, all = 1, 50000
>>> float(cnt) / all
2e-05
乘以100得到百分比。

假设您使用int(),那么Python总是向下取整。整数(0.99999)=0。从字面上讲,它只是删除小数点后的部分

如果您想要更像大多数人所说的四舍五入,您可以: “%0.0f”%(yourval,)


使用一个算法,它的名字从我这里逃脱,其中数字正好在中间向最近的偶数,所以0.5变成0,但是1.5变成2。0.49始终为0,0.51始终为1。

它会将答案向下舍入为0。

您的代码使用整数地板除法,它总是向零舍入

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

percentage = round((100.0*a) / sum(tally))

为了回答这个问题,我们需要了解您是如何计算百分比的,以及如何进行舍入。除非您发布代码,否则很难确定。这完全取决于进行舍入的内容。您是使用
print“%.2f”%value
还是某种字符串格式?好的,我将在问题中为您发布整个代码:)啊,感谢您的澄清,但是我不需要浮点值,因为我需要为每个百分点绘制一个带有*的直方图,我只是出于兴趣,再次感谢您:D