我正在计算列表中两个值之间的百分比差异。
#cal percentage dff: (val2/val)/100
values = [0.11889, 0.07485, 0.01070, 0.03076, 0.01606]
values = [int(round(i*100)) for i in values]
conversion_values = []
for x in range(1, len(values), 1):
val_1 = values[x-1]
if val_1 == 0.0: #Check if val_1 is 0.
conversion_values.append('-')
else:
val_2 = values[x]
diff = (val_2/val_1)*100
conversion_values.append(diff)
conversion_values
output:
[0, 0, 300, 0]
所需的输出:
[58, 14, 300, 67]
不确定我在做什么错吗?在Excel中,此计算工作正常,但在此处不行,必须与小数点有关?
注意-这不是关于百分比变化的问题,完全是另一回事。
答案 0 :(得分:3)
在执行(val_2)/val_1
时,您失去了精度,因此将其中之一转换为float以获得浮点数的最终结果,然后将结果转换为int
values = [0.11889, 0.07485, 0.01070, 0.03076, 0.01606]
values = [int(round(i*100)) for i in values]
conversion_values = []
for x in range(1, len(values), 1):
val_1 = values[x-1]
if val_1 == 0.0: #Check if val_1 is 0.
conversion_values.append('-')
else:
val_2 = values[x]
diff = int(round((float(val_2)/val_1)*100)) # change to float -->round--> int
conversion_values.append(diff)
conversion_values
输出:
[58, 14, 300, 67]
答案 1 :(得分:1)
好像您正在使用整数除法。 请重写此
diff = (val_2/val_1)*100
对此
diff = (val_2/float(val_1))*100
甚至对此
diff = (val_2/(val_1 * 1.0))*100