2016-12-15 152 views
2

我正在做几行数据的东西。这需要很长时间,我想显示进度的百分比。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%打印一次...

为什么会发生这种情况?我该如何解决它?

+4

[为什么不使用现成的图书馆?](https://pypi.python.org/pypi/tqdm) –

+3

如果您模拟repl中的前几个迭代,您将很容易地看到为什么 - 从第i + 1次迭代的第i次迭代可能轻松地从0.8%完成到1.2%完成,这两者都不是整数。 – Cameron

+0

嗯,看起来很不错。不过,还是很想知道答案:P –

回答

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()只对特定的值是真实的。

希望这会有所帮助!