如果不需要数字,如何删除数字前的0?

时间:2019-01-18 14:07:29

标签: python python-3.x

我正在编写一个程序,将所有可能的数字混合输出从0到9,如果输出少于6位,我想删除代码放在实际数字之前的数字。

我尝试在每个数组中将“”放在0之前,但也会在输出中放置随机空格。

Class1 = [0,1,2,3,4,5,6,7,8,9]
Class2 = [0,1,2,3,4,5,6,7,8,9]
Class3 = [0,1,2,3,4,5,6,7,8,9]
Class4 = [0,1,2,3,4,5,6,7,8,9]
Class5 = [0,1,2,3,4,5,6,7,8,9]
Class6 = [0,1,2,3,4,5,6,7,8,9]

for i in Class1:
    for j in Class2:
        for k in Class3:
            for l in Class4:
                for m in Class5:
                    for n in Class6:
                        print (i,j,k,l,m,n)

因此,我希望它输出的输出是895,而不是000895。它会达到100000,但这很合逻辑。

2 个答案:

答案 0 :(得分:2)

尽管以下代码可以帮助您采用类似的方法来解决问题,但我还是建议您采用另一种方式来实现所需的目标:

Class1 = [0,1,2,3,4,5,6,7,8,9]
Class2 = [0,1,2,3,4,5,6,7,8,9]
Class3 = [0,1,2,3,4,5,6,7,8,9]
Class4 = [0,1,2,3,4,5,6,7,8,9]
Class5 = [0,1,2,3,4,5,6,7,8,9]
Class6 = [0,1,2,3,4,5,6,7,8,9]

for i in Class1:
    for j in Class2:
        for k in Class3:
            for l in Class4:
                for m in Class5:
                    for n in Class6:
                        print(int(''.join([str(i),str(j),str(k),str(l),str(m),str(n)])))

上述方法利用了将单个数字转换为字符串,使用join()字符串方法将它们连接起来并将其重新转换为int的技巧。这样,像'0000001'这样的字符串将被转换为1

但是更好的方法是使用具有相同技巧的itertools.product()

import itertools
for seq in itertools.product([0,1,2,3,4,5,6,7,8,9], repeat=6):
    print(int(''.join([str(s) for s in seq])))

为简便起见,在join()里面我用list comprehension

答案 1 :(得分:0)

替换:

print (i,j,k,l,m,n)

通过:

print (100000*i+10000*j+1000*k+100*l+10*m+n)