alpha = [0,1,2,3,4,5,6,7,8,9]
for a in alpha:
for b in alpha:
for c in alpha:
for d in alpha:
print str(a) + str(b) + str(c) + str(d)
Run Code Online (Sandbox Code Playgroud)
上面的代码将生成0000到9999之间的所有数字.但是,我不喜欢代码的结构方式.假设我想这样做以产生最大十位数的数字; 这需要10个循环.有没有其他方法可以实现相同的结果,而无需插入无数的for循环?
显而易见的方式:
for i in xrange(10000): # or range if python 3
print "{0:04d}".format(i)
Run Code Online (Sandbox Code Playgroud)
您还可以将with指定为参数:
for i in xrange(10000): # or range if python 3
print "%0*d"%(4,i)
Run Code Online (Sandbox Code Playgroud)