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

2024-04-24 00:12:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个函数,把两个数字组之间的所有数字保存到一个文本文件中,其中有一个step选项,可以节省一些空间和时间,但我不知道如何显示百分比值,所以我尝试了这个方法。在

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伪变量,因为它只是为了中断循环;如果有其他表达式,我很抱歉。)第二部分是实际工作,我放入counter变量,然后用percent_quotient除以100,得到一个百分比。在

问题是,当我试图编一本长度从1到8的字典时,实际上要花一分钟数完所有的东西。我想如果我想编一本更大的字典,那要花更长的时间。在

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


Tags: tostepcounter数字lengthmaxfileint
2条回答

好吧,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,谢谢你,你的回答帮我解决了这个问题!在

我真搞不清这是怎么回事。但它看起来大致是这样做的:

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)
  • 不要用输出每个数字来压倒控制台,只打印一个状态更新,每一百个数字,或每一千个数字,大约。在
  • 少做str(int(str(int(str(int(str(int(...
  • 避免在紧循环中使用"" + blah,如果可能的话,它会导致每次都重建字符串,而且速度特别慢。在

相关问题 更多 >