Python:显示操作百分比

时间:2016-12-15 00:25:36

标签: python

我在几行数据上做了一些事情。这需要很长时间,我想显示进度的百分比。

所以我有以下代码:

for y in range(0, height):
    if (y * 100 / height).is_integer():
        print("... ", int(y * 100 / height), "%")

height是需要处理的行数。

然而,不知何故,此代码不会打印正确的百分比。如果高度为100,它可以正常工作。对于4050,它每2%打印一次(0%,2%,4%,...)。 2025年它每4%打印一次...

为什么会这样?我该如何解决?

1 个答案:

答案 0 :(得分:2)

对我的代码并不感到自豪,但无论如何:

last = -1 # Start it as -1, so that it still prints 0%.
for y in range(0, height):
    work = int(y * 100 / height) # I assigned the percentage to a variable for neatness.
    if work != last: # so it doesn't print the same percent over and over.
        print("... ", work, "%")
    last = work # Reset 'last'.

这可能/可能不完全准确。但它有效

您遇到问题的原因来自is_integer()仅对特定值有效。

希望这有帮助!

相关问题