【问题标题】:Python: Showing percentage of operation [duplicate]Python:显示操作百分比[重复]
【发布时间】:2016-12-15 00:25:35
【问题描述】:

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

所以我有以下代码:

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 个百分比打印一次...

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

【问题讨论】:

  • 如果你在 repl 中模拟前几次迭代,你会很容易明白为什么——从 ith 迭代到 i+1th 迭代可能很容易从 0.8%完成到 1.2%,两者都不是整数。
  • 嗯,看起来很不错。不过,很想知道答案:P
  • @leaf +1 介绍这个库 :)
  • @Cameron 该死的,这很有意义!太愚蠢了,我自己都没有意识到这一点。

标签: python


【解决方案1】:

我并不为我的代码感到骄傲,但无论如何:

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() 仅适用于特定值。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2018-03-01
    • 2017-12-07
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-26
    • 1970-01-01
    相关资源
    最近更新 更多