问题
I'm trying to generate all possible bytes to test for a machine learning algorithm (8-3-8 mural network encoder). is there a way to do this in python without having 8 loops?
Could permutations help?
I'd prefer an elegant way to do this, but I'll take what I can get at the moment.
desired output:
[0,0,0,0,0,0,0,0]
[0,0,0,0,0,0,0,1]
[0,0,0,0,0,0,1,0]
[0,0,0,0,0,0,1,1]
[0,0,0,0,0,1,0,0]
[0,0,0,0,0,1,0,1]
.
.
.
[1,1,1,1,1,1,1,1]
回答1:
Yes, there is, itertools.product:
import itertools
itertools.product([0, 1], repeat=8)
>>> list(itertools.product([0, 1], repeat=8))
[(0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 1),
[...]
(1, 1, 1, 1, 1, 1, 1, 0),
(1, 1, 1, 1, 1, 1, 1, 1)]
回答2:
[[x>>b&1 for b in range(8)] for x in range(256)]
回答3:
You could iterate over the numbers and then convert to binary:
[bin(x)[2:] for x in range(256)]
回答4:
If you happen to be using numpy already...
In [48]: import numpy as np
In [49]: nbits = 4
In [50]: np.sign(np.bitwise_and(2 ** np.arange(nbits), np.arange(2 ** nbits).reshape(-1, 1)))
Out[50]:
array([[0, 0, 0, 0],
[1, 0, 0, 0],
[0, 1, 0, 0],
[1, 1, 0, 0],
[0, 0, 1, 0],
[1, 0, 1, 0],
[0, 1, 1, 0],
[1, 1, 1, 0],
[0, 0, 0, 1],
[1, 0, 0, 1],
[0, 1, 0, 1],
[1, 1, 0, 1],
[0, 0, 1, 1],
[1, 0, 1, 1],
[0, 1, 1, 1],
[1, 1, 1, 1]])
来源:https://stackoverflow.com/questions/15538354/get-all-possible-single-bytes-in-python