#python #numpy
Вопрос:
Создайте следующий шаблон, начав с нулевой матрицы 5 на 5:
[5 0 0 0 5]
[5 0 0 0 5]
[5 0 0 0 5]
[5 5 5 5 5]]
my solution:
import numpy as np
x = np.zeros((5,5))
print(x)
result:
[[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]]
Я попытался добавить .добавить, чтобы я мог добавить 5, но идентификатор не сработал? Может ли кто-нибудь помочь мне решить эту проблему?
Комментарии:
1. Вместо того, чтобы начинать с матрицы нулей, я бы начал с матрицы 5s, что значительно упрощает эту проблему.
Ответ №1:
Вы можете сделать это с помощью небольшой функции:
import numpy as np
def create_matrix(matrixh: int, matrixw: int):
matrix = None
for row in range(matrixh):
if row in [(matrixh - 1), 0]: # Check if it's the first OR last row
newrow = np.full(matrixw, matrixh)
else: # The else block handles all of the rows in the middle
newrow = np.zeros(matrixw)
newrow[0] = matrixw # Set the first element to matrixw
newrow[matrixw - 1] = matrixw. # Set the last element to matrixw
# Add the new row to the stack
matrix = np.vstack([matrix, newrow]) if matrix is not None else newrow
return matrix
print(create_matrix(5,5))
print(create_matrix(6,6))
print(create_matrix(7,7))
выход:
[[5. 5. 5. 5. 5.]
[5. 0. 0. 0. 5.]
[5. 0. 0. 0. 5.]
[5. 0. 0. 0. 5.]
[5. 5. 5. 5. 5.]]
[[6. 6. 6. 6. 6. 6.]
[6. 0. 0. 0. 0. 6.]
[6. 0. 0. 0. 0. 6.]
[6. 0. 0. 0. 0. 6.]
[6. 0. 0. 0. 0. 6.]
[6. 6. 6. 6. 6. 6.]]
[[7. 7. 7. 7. 7. 7. 7.]
[7. 0. 0. 0. 0. 0. 7.]
[7. 0. 0. 0. 0. 0. 7.]
[7. 0. 0. 0. 0. 0. 7.]
[7. 0. 0. 0. 0. 0. 7.]
[7. 0. 0. 0. 0. 0. 7.]
[7. 7. 7. 7. 7. 7. 7.]]