我需要使用numpy在另一个矩阵中插入一个矩阵
我需要插入的矩阵如下所示:
tetraminos = [[0, 1, 0],
[1, 1, 1]]
而另一个矩阵是这样的:
board = numpy.array([
[6,0,0,0,0,0,0,0,0,0],
[6,0,0,0,0,0,0,0,0,0]
])
我实际使用的代码是:
board[0:0 + len(tetraminos), 0:0 + len(tetraminos[0])] = tetraminos
我得到的问题矩阵是:
wrong_matrix = numpy.array([
[[0,1,0,0,0,0,0,0,0,0],
[1,1,1,0,0,0,0,0,0,0]]
])
而预期的结果是:
expected_result = numpy.array([
[6,1,0,0,0,0,0,0,0,0],
[1,1,1,0,0,0,0,0,0,0]
])
错误在于,由于矩阵包含0,当我将其插入新矩阵时,我丢失了第一行的第一个值(数字6),而我想保留它
完整代码:
import numpy
if __name__ == '__main__':
board = numpy.array([
[6,0,0,0,0,0,0,0,0,0],
[6,0,0,0,0,0,0,0,0,0]
])
tetraminos = [[0, 1, 0], [1, 1, 1]]
board[0:0 + len(tetraminos), 0:0 + len(tetraminos[0])] = tetraminos
print(board)
expected_result = numpy.array([
[6,1,0,0,0,0,0,0,0,0],
[1,1,1,0,0,0,0,0,0,0]
])
exit(1)
您可以分两个步骤进行:
输出:
只要您始终希望在其中输入一个常量值,就可以将您的tetramino视为掩码并使用
np.putmask
函数:关于
putmask
的一个变体使用
tetraminos
作为布尔值来选择aview
的插槽以放置值:如果
tetraminos
具有其他非零值,则可以将其推广相关问题 更多 >
编程相关推荐