Mea*_*aty 5 python iteration loops
我写了一个函数,将两个数字组之间的所有数字保存到一个文本文件,带有一个步骤选项来节省一些空间和时间,我无法弄清楚如何显示一个百分比值,所以我尝试了这个.
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..."
Run Code Online (Sandbox Code Playgroud)
我在这里尝试做的是让程序像通常那样多次进行迭代,但是我只是将percent_quotient变量计算为迭代实际重复的次数,而不是写入文件.(我调用j
虚拟变量,因为它只是为了打破循环;如果有另一个表达式,我很抱歉.)第二部分是实际的工作,我把计数器变量,我把它除以percent_quotient
并乘以100到得到一个百分比.
问题是,当我试图从长度为1到长度为8的字典时,实际上花了一分钟来计算所有内容.我想如果我想制作更大的字典需要更长的时间.
我的问题是,有更好/更快的方法吗?
好吧,步骤变量让我很头疼,但如果没有它,这将是计算要写入多少数字的正确方法。
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
Run Code Online (Sandbox Code Playgroud)
TesselttingHeckler,谢谢您,您的回答帮助我解决了这个问题!