获取一个单元内矩阵值之间的差异
Get differences between matrix values within one unit
我有一个 nxm 列表的列表,我正在尝试计算一个单元内的每个值 i 和每个其他值 j 之间的差异,并将其添加到新列表中。我如何才能在 Python 中做到这一点?
让我们定义一个测试矩阵和一个函数来获取单元格的所有邻居:
m = [[i for i in range(10)] for i in range(10)]
# Size of "board"
X = len(m)
Y = len(m[0])
neighbors = lambda x, y : [(x2, y2) for x2 in range(x-1, x+2)
for y2 in range(y-1, y+2)
if (-1 < x <= X and
-1 < y <= Y and
(x != x2 or y != y2) and
(0 <= x2 <= X) and
(0 <= y2 <= Y))]
然后计算差异:
def get_differences(point, neigh, m):
px, py = point
return [m[px][py] - m[nx][ny] for nx, ny in neigh]
并测试两者的单点:
point = (1,1)
print('Neighbours: ', neighbors(*(point)))
print('Differences: ')
print(get_differences(point, neighbors(*(point)), m))
优雅的neighbors函数部分摘自this post.
我有一个 nxm 列表的列表,我正在尝试计算一个单元内的每个值 i 和每个其他值 j 之间的差异,并将其添加到新列表中。我如何才能在 Python 中做到这一点?
让我们定义一个测试矩阵和一个函数来获取单元格的所有邻居:
m = [[i for i in range(10)] for i in range(10)]
# Size of "board"
X = len(m)
Y = len(m[0])
neighbors = lambda x, y : [(x2, y2) for x2 in range(x-1, x+2)
for y2 in range(y-1, y+2)
if (-1 < x <= X and
-1 < y <= Y and
(x != x2 or y != y2) and
(0 <= x2 <= X) and
(0 <= y2 <= Y))]
然后计算差异:
def get_differences(point, neigh, m):
px, py = point
return [m[px][py] - m[nx][ny] for nx, ny in neigh]
并测试两者的单点:
point = (1,1)
print('Neighbours: ', neighbors(*(point)))
print('Differences: ')
print(get_differences(point, neighbors(*(point)), m))
优雅的neighbors函数部分摘自this post.