![](/img/trans.png)
[英]How do I create a binary matrix with a specific repeating pattern of 1s and 0s?
[英]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.resize
、 np.repeat
和np.eye
:
np.resize(np.repeat(np.eye(2), 4, axis = 0), (1000, 6))
np.resize
采用一种模式并将其在各个方向上复制到目标大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.