我需要找到单元格中所有相邻元素的总和,比如getsumofneighbors(matrix, i, j)
:
'M*N matrix'
[[0 1 0]
[2 0 1]
[0 4 0]
[0 0 0]]
单元格[0][0]
的最近元素之和为3
[1][0]
的是5
且[1][1]
为8
是否有python库可以找到给定单元格旁边所有元素的总和?
答案 0 :(得分:10)
如果您不介意对scipy的依赖,可以使用scipy.ndimage.convolve
,如下所示:
In [475]: a
Out[475]:
array([[0, 1, 0],
[2, 0, 1],
[0, 4, 0],
[0, 0, 0]])
In [476]: kernel
Out[476]:
array([[1, 1, 1],
[1, 0, 1],
[1, 1, 1]])
In [477]: from scipy.ndimage import convolve
In [478]: c = convolve(a, kernel, mode='constant')
In [479]: c
Out[479]:
array([[3, 3, 2],
[5, 8, 5],
[6, 3, 5],
[4, 4, 4]])
答案 1 :(得分:2)
您可以使用切片和np.sum
来计算特定区域的总和:
def getsumofneighbors(matrix, i, j):
region = matrix[max(0, i-1) : i+2,
max(0, j-1) : j+2]
return np.sum(region) - matrix[i, j] # Sum the region and subtract center
请注意,max
存在,因为负起始索引会触发不同的切片。
答案 2 :(得分:0)
def sum_neighbors(A, i, j):
rows, columns = A.shape
r0, r1 = max(0, i-1), min(rows-1, i+1)
c0, c1 = max(0, j-1), min(columns-1, j+1)
rs = list({r0, i, r1})
cs = [[c] for c in list({c0, j, c1})]
return A[rs, cs].sum() - A[i, j]
在A
之前和之后的i
之前和之后按行排序j
。取总和并减去i
,j
处的单元格。所有其他代码都是处理边缘。
import numpy as np
mxn = np.array([[0, 1, 0],
[2, 0, 1],
[0, 4, 0],
[0, 0, 0]])
for i, j in [(0, 0), (1, 0), (1, 1)]:
s = "sum of neigbors for i={} and j={} is {}"
print s.format(i, j, sum_neighbors(mxn, i, j))
sum of neigbors for i=0 and j=0 is 3
sum of neigbors for i=1 and j=0 is 5
sum of neigbors for i=1 and j=1 is 8
答案 3 :(得分:0)
以下函数应完成查找单元格中所有相邻元素之和的任务:
https://login.microsoftonline.com/common/oauth2/authorize?response_type=id_token&client_id=8613bd0c-93a9-46a3-a697-dd9ce9358f4f&client_secret=7lthp5nTenUOOW4uug4iEfe2x%2Fpxh8LwTZ%2FcSwPX%2F4A%3D&redirect_uri=https%3A%2F%2Fdodespacho.nubbius.com%2Fnubbius%2FO365OpenIDCallBack&state=2a25c9dc-fff5-4603-a755-3a0c9e92d499&nonce=b724a92a-d50b-4df2-a28e-5079ba858047&response_mode=form_post
关键点:
offsets定义了给定indice获取所需的相对更改 周围的元素(包括给定指标的位置,因为 相对变化[0] [0]导致指数没有变化)
由于偏移中的元素顺序,在此类中创建索引生成器对象 第一项是(0,0)的方式。第一项由next()
循环生成器对象剩余元素,计算和分配值 矩阵索引,如果索引不是,则将值添加到总计 否定(显而易见的原因)并且在指数持续时继续 超出范围(IndexError)
函数期望用户将在基于手指的索引中输入单元格位置 将值转换为基于0的索引
答案 4 :(得分:-1)
刚刚创建了这个可以完成工作的功能
def sumofnieghbors(MatrixObj, indexR, indexC):
upperleft = 0
if not (indexR < 1) or (indexC < 1):
upperleft = MatrixObj[indexR - 1][indexC - 1]
upper = 0
if not (indexR < 1):
upper = MatrixObj[indexR - 1][indexC]
upperright = 0
if not ((indexR < 1) or (indexC >= NbofCol)):
upperright = MatrixObj[indexR - 1][indexC + 1]
right = 0
if not (indexC >= NbofCol):
right = MatrixObj[indexR][indexC + 1]
rightdown = 0
if not ((indexR >= NbofRow) or (indexC >= NbofCol)):
rightdown = MatrixObj[indexR + 1][indexC + 1]
down = 0
if not (indexR >= NbofRow):
down = MatrixObj[indexR + 1][indexC]
leftdown = 0
if not ((indexR >= NbofRow) or (indexC < 1)):
leftdown = MatrixObj[indexR + 1][indexC - 1]
left = 0
if not (indexC < 1):
left = MatrixObj[indexR][indexC - 1]
return (upperleft + upper + upperright + right + rightdown + down + leftdown + left)