如果我有一個像這樣的 2 x 2 陣列:
1 2
3 4
我想把它加倍成一個 4 x 4 的陣列,如下所示:
1 1 2 2
1 1 2 2
3 3 4 4
3 3 4 4
或將其三重組成一個 6 x 6 陣列,如下所示:
1 1 1 2 2 2
1 1 1 2 2 2
1 1 1 2 2 2
3 3 3 4 4 4
3 3 3 4 4 4
3 3 3 4 4 4
等等等等......我將如何去做?
uj5u.com熱心網友回復:
不確定它是否是最好的解決方案,但絕對有效=p(您也可以只使用一個函式,我將其分開以使其更易于閱讀)
matrix = [[1, 2], [3, 4]]
def expand_array(input, multiplyer):
return [x for x in input for _ in range(multiplyer)]
def expand_matrix(input, multiplyer):
return [expand_array(x, multiplyer) for x in input for _ in range(multiplyer)]
print(matrix)
print(expand_matrix(matrix, 1))
print(expand_matrix(matrix, 2))
print(expand_matrix(matrix, 3))
print(expand_matrix(matrix, 4))
"""
[[1, 2], [3, 4]]
[[1, 2], [3, 4]]
[[1, 1, 2, 2], [1, 1, 2, 2], [3, 3, 4, 4], [3, 3, 4, 4]]
[[1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2], [3, 3, 3, 4, 4, 4], [3, 3, 3, 4, 4, 4], [3, 3, 3, 4, 4, 4]]
[[1, 1, 1, 1, 2, 2, 2, 2], [1, 1, 1, 1, 2, 2, 2, 2], [1, 1, 1, 1, 2, 2, 2, 2], [1, 1, 1, 1, 2, 2, 2, 2], [3, 3, 3, 3, 4, 4, 4, 4], [3, 3, 3, 3, 4, 4, 4, 4], [3, 3, 3, 3, 4, 4, 4, 4], [3, 3, 3, 3, 4, 4, 4, 4]]
"""
uj5u.com熱心網友回復:
您可以使用np.repeat:
a = [[1,2],
[3,4]]
dim_expand = 2 # double
b = np.repeat(a, dim_expand, axis=0).repeat(dim_expand, axis=1)
print(b)
"""
[[1 1 2 2]
[1 1 2 2]
[3 3 4 4]
[3 3 4 4]]
"""
dim_expand = 3 # triple
b = np.repeat(a, dim_expand, axis=0).repeat(dim_expand, axis=1)
print(b)
"""
[[1 1 1 2 2 2]
[1 1 1 2 2 2]
[1 1 1 2 2 2]
[3 3 3 4 4 4]
[3 3 3 4 4 4]
[3 3 3 4 4 4]]
"""
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/315948.html
