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

发布于 2025-01-24 06:08:39 字数 169 浏览 2 评论 0原文

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

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

How can I create a binary table of this alternating pattern efficiently in python? The 1s repeat for 4 elements then 0s for another 4 elements and so on and so forth as shown below:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

逆夏时光 2025-01-31 06:08:39

考虑使用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]])
"""

Consider using 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]])
"""
带刺的爱情 2025-01-31 06:08:39

使用列表理解:

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

您可能更喜欢使用0B101010和0B010101而不是字符串,但结果打印为42和21。

Using list comprehension:

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

You may prefer use 0b101010 and 0b010101 instead of string, but the result printed will be 42 and 21.

浪推晚风 2025-01-31 06:08:39

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

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

np.resize采用图案并将其朝目标尺寸复制到目标尺寸。

You can also use np.resize, np.repeat, and np.eye for this:

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

np.resize takes a pattern and copies it in every direction out to the target size.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文