繁体   English   中英

如何有效地创建具有特定 1 和 0 模式的二进制矩阵?

[英]How do I create binary matrix with specific pattern of 1s and 0s efficiently?

如何在 python 中有效地创建这种交替模式的二进制表? 1 对 4 个元素重复,然后 0 对另外 4 个元素重复,依此类推,如下所示:

101010 
101010
101010
101010
010101
010101
010101
010101
101010
101010
 ...

考虑使用numpy.tile

import numpy as np

one_zero = np.tile([1, 0], 12).reshape(4, 6)
"""
array([[1, 0, 1, 0, 1, 0],
       [1, 0, 1, 0, 1, 0],
       [1, 0, 1, 0, 1, 0],
       [1, 0, 1, 0, 1, 0]])
"""
zero_one = np.tile([0, 1], 12).reshape(4, 6)
"""
array([[0, 1, 0, 1, 0, 1],
       [0, 1, 0, 1, 0, 1],
       [0, 1, 0, 1, 0, 1],
       [0, 1, 0, 1, 0, 1]])
"""
ar = np.tile([[1, 0], [0, 1]], 12).reshape(8, 6)
"""
array([[1, 0, 1, 0, 1, 0],
       [1, 0, 1, 0, 1, 0],
       [1, 0, 1, 0, 1, 0],
       [1, 0, 1, 0, 1, 0],
       [0, 1, 0, 1, 0, 1],
       [0, 1, 0, 1, 0, 1],
       [0, 1, 0, 1, 0, 1],
       [0, 1, 0, 1, 0, 1]])
"""

使用列表理解:

table = [('101010', '010101')[x//4%2 == 1] for x in range(100)]

您可能更喜欢使用 0b101010 和 0b010101 而不是字符串,但打印的结果将是 42 和 21。

您还可以为此使用np.resizenp.repeatnp.eye

np.resize(np.repeat(np.eye(2), 4, axis = 0), (1000, 6))

np.resize采用一种模式并将其在各个方向上复制到目标大小。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM