【问题标题】:get all possible single bytes in python在python中获取所有可能的单字节
【发布时间】:2013-03-21 11:21:39
【问题描述】:

我正在尝试生成所有可能的字节来测试机器学习算法(8-3-8 壁画网络编码器)。有没有办法在没有 8 个循环的情况下在 python 中做到这一点?

排列有帮助吗?

我更喜欢一种优雅的方式来做到这一点,但我会尽我所能。

想要的输出:

[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]

【问题讨论】:

  • 另外,顺序并不重要!只是为了让我每个人都有一个!

标签: python byte combinations


【解决方案1】:

是的,有,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)]

【讨论】:

  • @DSM 再次感谢,我没注意。
【解决方案2】:
[[x>>b&1 for b in range(8)] for x in range(256)]

【讨论】:

    【解决方案3】:

    您可以遍历数字,然后转换为二进制:

    [bin(x)[2:] for x in range(256)]
    

    【讨论】:

      【解决方案4】:

      如果你碰巧已经在使用 numpy...

      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]])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-26
        • 1970-01-01
        • 1970-01-01
        • 2011-05-16
        • 2015-02-16
        • 1970-01-01
        • 1970-01-01
        • 2018-08-10
        相关资源
        最近更新 更多