Gen*_*ral 5 python numpy scipy
对于每个矩阵元素,我想添加其所有相邻单元格的值。
从我的初始数组开始
board = np.array([[0, 1, 1],
[0, 1, 0],
[1, 0, 0]])
Run Code Online (Sandbox Code Playgroud)
我的结果应该是:
([2,2,2],
[3,3,3],
[1,2,1])
Run Code Online (Sandbox Code Playgroud)
我创建了一个函数并使用蛮力方法来查找其周围是否存在单元格。如果是,则将这些值相加并返回总数。我不确定我是否正确地处理我的 if 语句。它说以下错误
'具有多个元素的数组的真值不明确:使用 a.any() 或 a.all()'
def count_living_neighbors(board):
count = np.zeros(board.shape, dtype=int)
#
# YOUR CODE HERE
#
for row in range(len(board)):
for column in range(len(board[row])):
total = 0
if (board[column - 1]).any() in board:
total += board[row][column-1]
if (board[column + 1]).any() in board:
total += board[row][column+1]
if (board[row - 1]).any() in board:
total += board[row-1][column]
if (board[row + 1]).any() in board:
total += board[row+1][column]
if (board[row + 1] and board[column - 1]).any() in board:
total += board[row+1][column-1]
if (board[row - 1] and board[column - 1]).any() in board:
total += board[row-1][column-1]
if (board[row + 1] and board[column + 1]).any() in board:
total += board[row+1][column+1]
if (board[row - 1] and board[column + 1]).any() in board:
total += board[row+1][column+1]
count[row][column] = total
return count
Run Code Online (Sandbox Code Playgroud)
您可以scipy.signal.convolve使用mode='same':
from scipy import signal
kernel = np.ones((3, 3), dtype=np.int8)
kernel[1, 1] = 0
print(signal.convolve(board, kernel, mode='same'))
[[2 2 2]
[3 3 3]
[1 2 1]]
Run Code Online (Sandbox Code Playgroud)
这里kernel看起来像这样:
array([[1, 1, 1],
[1, 0, 1],
[1, 1, 1]], dtype=int8)
Run Code Online (Sandbox Code Playgroud)
无论 的形状如何,都将是相同的board。基本上,kernel指的是邻居的位置(相对于中心的 0)。
Mag*_*n88 -1
尝试 scipy.signal.convolve2d 类似的东西
convolve2d( yourMatrix, np.ones((3,3))
Run Code Online (Sandbox Code Playgroud)
应该做的伎俩