get all possible single bytes in python

萝らか妹 提交于 2019-12-22 11:04:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!