当使用多个嵌套for循环时,如何在python中绕过静态嵌套块?

时间:2017-02-06 18:31:36

标签: python for-loop nested

好的,我正在研究一个二进制最多3个字节的程序。我这样做是为了找出3个字节的组合总数,仅用于个人知识。目前,我有

def test(): #nested forloop binary counter;
input1 = 2
counter = 1
for a in range(input1):
    for b in range(input1):
        for c in range(input1):
            for d in range(input1):
                for e in range(input1):
                    for f in range(input1):
                        for g in range(input1):
                            for h in range(input1): #H = 8, 1 Byte
                                for i in range(input1):
                                    for j in range(input1):
                                        for k in range(input1):
                                            for l in range(input1):
                                                for m in range(input1):
                                                    for n in range(input1):
                                                        for o in range(input1):
                                                            for p in range(input1): #P = 16, 2 Bytes
                                                                for q in range(input1):
                                                                    for r in range(input1):
                                                                        for s in range(input1):
                                                                            for t in range(input1):
                                                                                for u in range(input1):
                                                                                    for v in range(input1):
                                                                                        for w in range(input1):
                                                                                            for x in range(input1): #X = 24, 3 Bytes
                                                                                                print(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,'    ',counter)
                                                                                                counter = counter + 1

当我尝试运行它时,它会给我一个错误:"太多的静态嵌套块"。那么有没有办法以相同的效果解决这个问题,但没有所有嵌套的for循环?

1 个答案:

答案 0 :(得分:5)

使用itertools.product

>>> from itertools import product
>>> for comb in product('01', repeat=24):
...     print(''.join(comb))
...
000000000000000000000000
000000000000000000000001
000000000000000000000010
000000000000000000000011
000000000000000000000100
...

甚至更好的二进制转换:

>>> for i in range(2**24):
...     print(bin(i)[2:].zfill(24))
...
000000000000000000000000
000000000000000000000001
000000000000000000000010
000000000000000000000011
000000000000000000000100
...