我写了一个函数,把两个数字组之间的所有数字保存到一个文本文件中,其中有一个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的字典时,实际上要花一分钟数完所有的东西。我想如果我想编一本更大的字典,那要花更长的时间。在
我的问题是,有没有更好/更快的方法?在
好吧,step变量让我很头疼,但是没有它,这将是计算要写多少个数字的正确方法。在
TessellatingHeckler,谢谢你,你的回答帮我解决了这个问题!在
我真搞不清这是怎么回事。但它看起来大致是这样做的:
如果这是对的,那么我建议:
string.zfill()
代替while len(str(num)) < length: "0" + str(num)
str(int(str(int(str(int(str(int(...
"" + blah
,如果可能的话,它会导致每次都重建字符串,而且速度特别慢。在相关问题 更多 >
编程相关推荐