繁体   English   中英

如何在 python 中有效地重复矩阵中的二进制模式和比率?

[英]How do I repeat binary pattern and ratio in matrix effectively in python?

我想在 python 中高效地打印一个矩阵,该矩阵遵循 5 个 0 列中的特定模式,然后是 3 个 1,然后是 5 个 0,依此类推,如下所示 1000 行:

0000
0000
0000
0000
0000
1111
1111
1111
0000
0000
0000
0000
0000
1111
1111
1111
...

您可以结合使用np.block和列表理解:

out = np.block([[np.zeros((5, 4))],[np.ones((3, 4))]] * 125).astype(int)

这可以被功能化以回答类似的问题,如下所示:

def block_repeat(size, *args):
    block = np.block([[a] for a in args])
    return np.resize(block, (size,) + block.shape[1:])

block_repeat(1000, np.zeros((5,4)), np.ones((3,4)))
Out[]: 
array([[0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.],
       ...,
       [1., 1., 1., 1.],
       [1., 1., 1., 1.],
       [1., 1., 1., 1.]])

这没有使用numpy但它完成了工作。 您稍后可以使用numpy.matrix将其转换为numpy matrix

import itertools

cycle = itertools.cycle([("0") for i in range(5)] + [("1") for i in range(3)])

for i in range(1000):
  item = next(cycle)
  print(4 * item)

Output -

00000
00000
00000
00000
00000
11111
11111
11111
00000
00000
00000
00000
00000
11111
11111
11111

以下是您的操作方法:

import numpy as np

my_array = np.array([[[0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0], [1,1,1,1], [1,1,1,1], [1,1,1,1]] for i in range(125)])

你可以检查形状。 它有 125 行 8 行即 1000:

>>> my_array.shape
(125, 8, 4)

要打印它,您可以使用:

count_row = 0
for row in my_array:
    for row2 in row:
        print(row2)
        count_row += 1

Output:

# count_row is equal to 1000.

[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[1 1 1 1]
[1 1 1 1]
[1 1 1 1]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[1 1 1 1]
[1 1 1 1]
[1 1 1 1]
[0 0 0 0]
....

本着@Ishan 打高尔夫球的精神,这里是一行,没有图书馆:

print("\n".join(["00000111"[i % 8] * 4 for i in range(1000)]))

# Explanation
pattern = "00000111"
for i in range(1000):
    index = i % len(pattern)
    print(pattern[index] * 4)

使用np.tile ,您甚至可以避免使用列表理解:

>>> unit = np.repeat([0] * 5 + [1] * 3, 4)
>>> # you can also use unit = [0] * 20 + [1] * 12,
>>> # but using ndarray as the parameter of np.tile is faster than list.
>>> np.tile(unit, 2).reshape(-1, 4)
array([[0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0],
       [1, 1, 1, 1],
       [1, 1, 1, 1],
       [1, 1, 1, 1],
       [0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0],
       [1, 1, 1, 1],
       [1, 1, 1, 1],
       [1, 1, 1, 1]])
>>> np.tile(unit, 125).reshape(-1, 4)
array([[0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0],
       ...,
       [1, 1, 1, 1],
       [1, 1, 1, 1],
       [1, 1, 1, 1]])

暂无
暂无

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

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