如何在Python中迭代bytearray of length = n
的所有可能值?
在最坏的情况下n <= 40bytes
例如,迭代n = 4
:
00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000001
00000000 00000000 00000000 00000010
.
.
.
.
11111111 11111111 11111111 11111110
11111111 11111111 11111111 11111111
答案 0 :(得分:4)
您可以使用itertools.product
:
In [11]: from itertools import product
In [15]: for x in product('01',repeat=4): #for your n=4 change repeat to 32
print "".join(x)
....:
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
答案 1 :(得分:2)
受https://stackoverflow.com/a/15538456/1219006启发
n = 2
[[[i>>k&1 for k in range(j, j-8, -1)] for j in range(8*n-1, 0, -8)]
for i in range(2**(8*n))]
您需要在Python 3上针对较大的n
运行此操作,因为xrange
不支持大整数。
作为发电机:
def byte_array(n):
for i in range(2**(8*n)):
yield [[i>>k&1 for k in range(j, j-8, -1)] for j in range(8*n-1, 0, -8)]
>>> i = byte_array(4)
>>> next(i)
[[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]
>>> next(i)
[[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1]]
或者,如果您不希望它们分组,则更简单:
[[i>>j&1 for j in range(8*n-1, -1, -1)] for i in range(2**(8*n))]
等效发电机:
def byte_array(n):
for i in range(2**(8*n)):
yield [i>>j&1 for j in range(8*n-1, -1, -1)]