计算迭代操作百分比的最佳方法是什么?

时间:2015-06-19 21:40:24

标签: python loops iteration

我编写了一个功能,可以将两个数字组之间的所有数字保存到文本文件中,并带有一个步骤选项来节省一些空间和时间,我无法弄清楚如何显示百分比值,所以我试过了。

for length in range(int(limit_min), int(limit_max) + 1):

    percent_quotient = 0
    j=0
    while j <= (int(length * "9")):
        while len(str(j)) < length:
            j = "0" + str(j)  

        percent_quotient+=1
        j = int(j) + int(step)  # increasing dummy variable

for length in range(int(limit_min), int(limit_max) + 1):
    counter=1
    i = 0
    while i <= (int(length * "9")):
        while len(str(i)) < length:
            i = "0" + str(i)  #

        print "Writing %s to file. Progress: %.2f percent." % (str(i),(float(counter)/percent_quotient)*100)
        a.write(str(i) + "\n")  # this is where everything actually gets written
        i = int(i) + int(step)  # increasing i
        counter+=1
    if length != int(limit_max):
        print "Length %i done. Moving on to length of %i." % (length, length + 1)
    else:
        print "Length %i done." % (length)
a.close()  # closing file stream
print "All done. Closed file stream. New file size: %.2f megabytes." % (os.path.getsize(path) / float((1024 ** 2)))
print "Returning to main..."

我在这里尝试做的是让程序像通常那样多次进行迭代,但是我只是将percent_quotient变量计算为迭代实际重复的次数而不是写入文件。 (我打电话给j虚拟变量,因为它只会打破循环;如果有另一个表达式,我很抱歉。)第二部分是实际工作,我把计数器变量,我将其除以percent_quotient并乘以100得到一个百分比。

问题是,当我尝试从长度为1到长度为8的字典时,实际上花了一分钟来计算所有内容。我想如果我想制作更大的字典需要更长的时间。

我的问题是,有更好/更快的方法吗?

2 个答案:

答案 0 :(得分:3)

我无法弄清楚这是做什么的。但它看起来大致如此:

a = file('d:/whatever.txt', 'wb')
limit_min = 1
limit_max = 5
step = 2

percent_quotient = (10 ** (limit_max - limit_min)) / step

for i in range(limit_min, 10**limit_max, step):
    output = str(i).zfill(limit_max) + '\r\n'
    a.write(output)

    if i % 100 < 2:
        print "Writing %s to file. Progress: %.2f percent." % (str(i),(float(i)/percent_quotient)*100)

a.close()

如果那是对的,那么我建议:

  • 减少代码循环和更多数学
  • 使用string.zfill()代替while len(str(num)) < length: "0" + str(num)
  • 不要用每一个数字的输出来压倒控制台,只打印每100个数字或每千个数字左右的状态更新。
  • 少做str(int(str(int(str(int(str(int(...
  • 避免"" + blah在紧密循环中,如果可能的话,它会导致每次重建字符串并且速度特别慢。

答案 1 :(得分:0)

好吧,step变量让我很头疼,但没有它,这将是计算将要编写多少数字的正确方法。

percent_quota=0  #starting value    
for i in range(limit_min,limit_max+1):  #we make sure all lengths are covered
    percent_quota+=(10**i)-1  #we subtract 1 because for length of 2, max is 99

TessellatingHeckler,谢谢你,你的答案帮我解决了这个问题!

相关问题