对于我必须为 CodeSignal 再次编写的函数,我使用 numpy 创建一个名为“结果”的“空”矩阵。在 for 循环过程中,我想向该零矩阵的某些元素添加 1:
matrix = [[True, False, False],
[False, True, False],
[False, False, False]]
matrix = np.array(matrix) ## input matrix
(row, col) = matrix.shape
result = np.zeros((row,col), dtype=int) ## made empty matrix of same size
for i in range(0, row):
for j in range(0, col):
mine = matrix[i,j],[i,j]
if mine[0] == True: ##for indices in input matrix where element is called True..
result[i+1,j+1][i+1,j+1] = 1 ##..replace neighbouring elements with 1 (under construction ;) )
print(result)
我的第一个问题来自最后一部分,用另一个值替换给定索引处的元素。 例如。结果[1,1][1,1] = 1 我总是收到错误
TypeError: object does not support item assignment
这是在将 np.zeros 设置为各种对象类型之后发生的 - int32、int8、complex、float64...
如果我尝试:
例如结果[1,1][1,1]==1
我得到:
IndexError: invalid index to scalar variable.
那么如何在特定位置更改或添加元素到 2d np 数组呢?
最佳答案
这样写是没有意义的:
matrix[i,j][i,j]
矩阵是一个二维数组,因此这意味着matrix[i,j]
是一个标量,而不是一个数组。应用 0[i,j]
是没有意义的。
您可以将其实现为:
for i in range(row<b>-1</b>):
for j in range(col<b>-1</b>):
if matrix[i,j]:
result[i+1,j+1] = 1
因此,您将在这里将 matrix
的值向右“移动”一位,向下移动一位。但你最好用以下方法执行此操作:
result[1:,1:] = matrix[:-1,:-1]
这给了我们:
>>> result
array([[0., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
关于python - Numpy 零二维数组 : substituting elements at specific indices,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60177876/