我想在 python 中有效地列印一個矩陣,該矩陣在 5 0s 然后 3 1s 然后 5 0s 等列中遵循特定模式,依此類推,如下所示 1000 行:
0000
0000
0000
0000
0000
1111
1111
1111
0000
0000
0000
0000
0000
1111
1111
1111
...
uj5u.com熱心網友回復:
您可以結合使用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.]])
uj5u.com熱心網友回復:
以下是您的操作方法:
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
輸出:
# 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]
....
uj5u.com熱心網友回復:
這沒有用numpy,但它完成了作業。您可以稍后將其轉換為numpy matrixusing 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)
輸出 -
00000
00000
00000
00000
00000
11111
11111
11111
00000
00000
00000
00000
00000
11111
11111
11111
uj5u.com熱心網友回復:
本著@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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464608.html
上一篇:這里的廣播順序是什么?
